C++ lanuage only Part 1 Write a program that uses a recursive function to conver
ID: 3812742 • Letter: C
Question
C++ lanuage only Part 1 Write a program that uses a recursive function to convert a number in decimal to a given base b, where b is 2, 8, or 16. Your program should prompt the user to enter the number in decimal and the desired base. Test your program on the following data: 9098 and base 8 692 and base 2 753 and base 16 Sample output: Please enter a number? 4598 Please enter a base between 2 and 16? 8 The decimal number 4598 is equal to 10766 in base 8. Please enter a number? 25354 Please enter a base between 2 and 16? 16 The decimal number 4598 is equal to 630A in base 16.
Explanation / Answer
#include <iostream>
using namespace std;
int convert(int,int); // funcrion to convert decimal to base b
int main()
{
int dec, base, con;
cout<<"Please enter a number?";
cin>>dec;
cout<<"Please enter a base between 2 and 16?";
cin>>base;
con = convert(dec,base);
if(con != 0)
cout<<"The decimal number "<<dec<<" is equal to "<< con<<" in base "<<base<<" ";
return 0;
}
int convert(int dec, int base)
{
char hexadecimalnum[100];
int quotient, remainder;
int i, j = 0;
if (dec == 0){
return 0;
}
else{
if(base == 16){ // for hexa decimal numbers
quotient = dec;
while (quotient != 0){
remainder = quotient % 16;
if (remainder < 10)
hexadecimalnum[j++] = 48 + remainder;
else
hexadecimalnum[j++] = 55 + remainder;
quotient = quotient / 16;
}
// display integer into character
cout<<"The decimal number "<<dec<<" is equal to ";
for (i = j-1; i >= 0; i--){
cout<<hexadecimalnum[i];
}
cout<<" in base "<<base<<" ";
return 0;
}
else{
return (dec % base + 10 * convert((dec / base),base)); // for the rest of bases
}
}
}
/*
Output :-
Please enter a number?9098
Please enter a base between 2 and 16?8
The decimal number 9098 is equal to 21612 in base 8
Please enter a number?692
Please enter a base between 2 and 16?2
The decimal number 692 is equal to 1010110100 in base 2
Please enter a number?753
Please enter a base between 2 and 16?16
The decimal number 753 is equal to 2F1 in base 16
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.