In: Computer Science
C++
[2] Write a program that prompts the user to enter a
non-negative decimal number and a base in the range 2 <= base
<= 16. Write a function multibaseOutput() that displays the
number in the specified base. The program terminates when the user
enters a number of 0 and a base 0.
Run:
Enter a non-negative decimal number and base (2 <= B <= 16)
or 0 0 to terminate: 155 16
155 base 16 is 9B
Enter a non-negative decimal number and base (2 <= B <= 16)
or 0 0 to terminate: 3553 8
3553 base 8 is 6741
Enter a non-negative decimal number and base (2 <= B <= 16)
or 0 0 to terminate: 0 0
ANSWER:-
#include <iostream>
#include <string.h>
using namespace std;
// To return char for a value. For example '2'
// is returned for 2. 'A' is returned for 10. 'B'
// for 11
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else
return (char)(num - 10 + 'A');
}
// Utility function to reverse a string
void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
{
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
// Function to convert a given decimal number
// to a base 'base' and
char* fromDeci(char res[], int base, int inputNum)
{
int index = 0; // Initialize index of result
// Convert input number is given base by repeatedly
// dividing it by base and taking remainder
while (inputNum > 0)
{
res[index++] = reVal(inputNum % base);
inputNum /= base;
}
res[index] = '\0';
// Reverse the result
strev(res);
return res;
}
// Driver program
int main()
{
int Num,base;
char res[100];
do
{
cout<<"Enter a non-negative decimal number and base (2 <=
B <= 16) or 0 0 to terminate : ";
cin>>Num>>base;
cout<<Num<<" base "<<base<<" is
"<<fromDeci(res, base, Num);
}while(Num!=0 && base!=0);
return 0;
}
OUTPUT:-
// If any doubt please comment