In: Computer Science
In C programming
Generalize the to binary() function of Listing 9.8 (from your textbook) to a to base n(number, base) function that takes a second argument in the range 2–10. It then should convert (and print) the number that is its first argument to the number base given by the second argument. For example, to base n(129,8) would display 201, the base-8 equivalent of 129. Test the function in a complete program.
#include<stdio.h>
#include<math.h> //FOR POW FUNCTION
int toBaseN(int number, int base)
{
int j, convertedNumber = 0, tmp, digit;
j = 0;
tmp = number;
while(tmp != 0)
{
digit = tmp % base;
tmp = tmp / base;
convertedNumber = convertedNumber + (digit * pow(10, j));
j++;
}
return convertedNumber;
}
int main()
{
int number, base, convertedNumber;
//TAKING INPUT FROM USER
printf("Enter the number: ");
scanf("%d", &number);
printf("\nEnter the base in which you want to convert(2 - 10): ");
scanf("%d", &base);
//CONVERTING THE NUMBER TO BASE N
convertedNumber = toBaseN(number, base);
//PRINTING THE RESULT
printf("\nThe number %d in base %d is: %d\n", number, base, convertedNumber);
}
NOTE: This is the required C program, and if you are having problem in running the program, please comment.
PLEASE UPVOTE IF YOU LIKED THE ANSWER.