lolamontes69

K+R Exercise3_6

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