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?
That is a better idea to use a buffer to write your solution:
You must write backward in your buffer (or write forward, then reverse the string) because with your method, you have the smallest digit first.