/* A program to convert a non-negative base 10 number into a base b (where 
 * b >= 2)
 */

#include <stdio.h>

int main()
{
  int a, b, i, numDigits, aTemp;
  int* digits;

  /* User input */

  printf("Enter the number to be converted: ");
  scanf("%d", &a);
  if (a < 0)
  {
    printf("ERROR: the number must be non-negative\n");
    return(1);
  }

  printf("Enter the base: ");
  scanf("%d", &b);
  if (b < 2)
  {
    printf("ERROR: the base must be greater than or equal to 2\n");
    return(2);
  }

  /* We need to determine how many digits the converted number will have. 
   * There are several ways to do this. Here I've just run through the 
   * basic algorithm (without bothering to compute the digits themselves; 
   * we'll do that later) in order to determine how many steps it takes.
   */

  numDigits = 0;
  aTemp = a;
  while (aTemp > 0)
  {
    aTemp = aTemp/b;
    numDigits++;
  }

  digits = new int[numDigits];

  /* Now we run through the actual algorithm. The digits are the remainder 
   * when a is divided by b. Then we let the "new" a be the quotient when 
   * a is divided by b. We continue in this manner until a = 0. Note that 
   * I use aTemp here (set to the value of the inputted a) rather than a 
   * itself only because I want to save the original value of a for output 
   * later.
   */

  aTemp = a;
  for (i = 0; i < numDigits; i++)
  {
    digits[i] = aTemp%b;
    aTemp = aTemp/b;
  }

  /* Output */

  printf("The number %d in base %d is: ", a, b);
  for (i = numDigits-1; i >= 0; i--)
  {
    printf("%d", digits[i]);
  }
  printf("\n");

  return(0);
}

