Path: blob/master/languages/cprogs/Ex_3.4_itoa-2.c
1240 views
/* Modified version of itoa; to handle the situation of MIN_INT of limits.h1in the previous number = -2147483648 would fail at n =-n,because the max value of integer is 214748364723modifying itoa to handle these situations.4sign is stored as the number itself, absolute value of each digit is stored in the string and5while loop is tested not for 067itoa: convert an integer to string */89#include<stdio.h>10#include<string.h>11#define MAXLINE 10001213#define abs(x) ( (x) > 0 ? (x): -(x))1415void itoa(int n,char s[]);16void reverse(char s[]);171819int main(void)20{21int number;22char str[MAXLINE];2324/* number=-2345645; */2526number = -2147483648;272829printf("Integer %d printed as\n String:",number);3031itoa(number,str);3233printf("%s",str);3435return 0;36}3738void itoa(int n,char s[])39{40int i,sign;4142sign=n;4344i = 0;4546do47{48s[i++]= abs(n%10) + '0';4950}while((n/=10)!=0);5152if( sign < 0)53s[i++]='-';5455s[i]='\0';5657reverse(s);58}5960void reverse(char s[])61{62int c,i,j;6364for(i=0,j=strlen(s)-1;i<j;i++,j--)65c=s[i],s[i]=s[j],s[j]=c;66}67686970