2

I need to write a program in C language that will take a natural number n and base b(assuming b is in the interval [2,10]) and will output the digits of the number n in base b, from left to right. For example, if n=38 and b=3, the output should be 1102. This is what I have tried:

#include<stdio.h>

int main(void) {

    int n,b,number=0,digit=0;
    scanf("%d", &n);
    scanf("%d", &b);

    while(n>0) {
    digit=n%b;
    number=number*10+digit;
    n=n/b;
    }

    while(number>0) {
    printf("%d", number%10);
    number=number/10;
    }

    return 0;
}

This works for n=38 and b=3, but if I take for example n=8 and b=2, the output is 1, when it should be 1000. How do I fix this?

lmc
  • 175
  • 2
  • 8
  • 1
    Your approach works only when `n` is not evenly divisible by the base. Additionally, it breaks for large(ish) numbers expressed in small bases, because then you can easily overflow the capacity of `number`. I suggest computing digits in the opposite order -- from least to most significant -- and storing them in an array, along with maintaining a count of how many there are. I'm sure you can then work out for yourself how to output the result. – John Bollinger Dec 19 '16 at 17:47
  • try reading this first http://stackoverflow.com/documentation/c/8269/debugging#t=201612191007287 – NeoR Dec 19 '16 at 17:49
  • I saw this one,, I saw this one...ah, here it is: http://stackoverflow.com/questions/21133701/is-there-any-function-in-the-c-language-which-can-convert-base-of-decimal-number It's done recursively but you can do it linearly, too. – deamentiaemundi Dec 19 '16 at 17:57

1 Answers1

2

That is a better idea to use a buffer to write your solution:

void print_base(int n, int b)
{
  static char const digits[] = "0123456789ABCDEF";
  char buffer[16] = { '\0' };
  char * buff = buffer + 15;

  if ((b >= sizeof digits) || (b <= 1))
    return; // error
  for (; n > 0; n /= b)
    *--buff = digits[n % b]; // move the char pointer backward then write the next digit
  printf("%s\n", buff);
}

You must write backward in your buffer (or write forward, then reverse the string) because with your method, you have the smallest digit first.

Boiethios
  • 38,438
  • 19
  • 134
  • 183