lolamontes69

K+R Exercise3_5

Sep 7th, 2014
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void itob(int n, char s[], int b);
  5. void reverse(char s[]);
  6.  
  7. int main()
  8. {
  9.     int n, b;
  10.     char s[255];
  11.  
  12.     printf("Enter the integer     :");
  13.     scanf("%d",&n);
  14.     printf("Enter the base number :");
  15.     scanf("%d",&b);
  16.     if(b>36) puts("I can only do up to base 36");
  17.     else itob(n,s,b);
  18.     return(0);
  19. }
  20.  
  21. void itob(int n, char s[], int b)
  22. {
  23.     int index, remainder;
  24.     char nstr[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g',
  25.                    'h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x',
  26.                    'y','z'};
  27.  
  28.     remainder = 0;
  29.     index     = 0 ;
  30.     while ( n != 0 )
  31.         {
  32.             remainder = n % b ;  // assume K > 1
  33.             n         = n / b ;  // integer division
  34.             s[index] = nstr[remainder];
  35.             index ++ ;
  36.     }
  37.     s[index] = '\0';
  38.     reverse(s);
  39.  
  40. }
  41.  
  42. void reverse(char s[])
  43. {
  44.     int c, i, j;
  45.  
  46.     for(i=0, j = strlen(s)-1; i<j; i++, j--) {
  47.         c = s[i];
  48.         s[i] = s[j];
  49.         s[j] = c;
  50.     }
  51.     puts("\nReversed i.e., 'correct way round'");
  52.     for(i=0; i<strlen(s); i++)
  53.         printf("%c",s[i]);
  54.     puts(" ");
  55. }
Advertisement
Add Comment
Please, Sign In to add comment