Write a program in C that takes a natural number n and base b and outputs digits of n in b

232 views Asked by At

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?

1

There are 1 answers

0
Boiethios On BEST ANSWER

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.