lolamontes69

K+R Exercise3_4

Sep 7th, 2014
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void itoa(int n, char s[]);
  5. void reverse(char s[]);
  6.  
  7. int main()
  8. {
  9.     int n;
  10.     char s[244];
  11.    
  12.     printf("Enter the integer :");
  13.     scanf("%d",&n);
  14.  
  15.     itoa(n,s);
  16.     return(0);
  17. }
  18.  
  19. /* Convert an integer into a character string (reversed eg 987 == '789') */
  20. void itoa(int n, char s[])
  21. {
  22.     int i, sign;    
  23.     int LNN = 0;  /* Largest negative number or less */
  24.  
  25.     if((sign=n)<0)
  26.         n = -n;
  27.     if(n<0) {
  28.         n = -(n+1); /* otherwise is larger than largest positive number */
  29.         LNN=1;
  30.     }
  31.     i=0;
  32.     do {
  33.         if(LNN && i==0) s[i++] = n % 10 + '0' + 1;  /* correct if LNN */
  34.         else s[i++] = n % 10 + '0';  
  35.     } while((n/=10)>0);
  36.     if(sign<0)
  37.         s[i++]='-';
  38.     s[i] = '\0';
  39.  
  40.     reverse(s);
  41. }
  42.  
  43.  
  44. /* reverse: reverse string s in place */
  45. void reverse(char s[])
  46. {
  47.     int c, i, j;
  48.  
  49.     for(i=0, j = strlen(s)-1; i<j; i++, j--) {
  50.         c = s[i];
  51.         s[i] = s[j];
  52.         s[j] = c;
  53.     }
  54.     puts("\nReversed");
  55.     for(i=0; i<strlen(s); i++)
  56.         printf("%c",s[i]);
  57.     puts(" ");
  58. }
Advertisement
Add Comment
Please, Sign In to add comment