**C++ only** Assignment: For this assignment you’ll be designing a program which
ID: 3905508 • Letter: #
Question
**C++ only**
Assignment: For this assignment you’ll be designing a program which can take the input of a decimal number and a numerical base, and convert the decimal number to that base. For example, if given the decimal number seven and the base two, your program should output it as 111, which is how seven is represented in binary. Another example, 8,943 in base 10, is 13,236 in base 9. You’ll need to perform these operations on the following combinations
: A: 15, base 2.
B: 38, base 16.
C: 54, base 6.
D: 19, base 8.
E: 27, base 3.
Explanation / Answer
#include<iostream>
#include <cstdio>
using namespace std;
// recursive function to compute Number to any base
void convert(int Number, int base)
{
// base case
if (Number == 0)
return;
// compute last digit
int rem = Number % base;
Number /= base;
// if last digit<0 add 1 to number
if (rem < 0)
Number += 1;
// recursive call to convert function
convert(Number, base);
// print if rem <0 then rem*(-base) else rem from stack
// cout<< rem < 0 ? rem + (base * -1) : rem;
if(rem<0)
cout<<rem + (base * -1);
else
cout<<rem;
return;
}
int main()
{
int Number;
int base;
cout<<"Enter number in decimal base: ";
cin>>Number;
cout<<"Enter base to convert: ";
cin>>base;
if(Number<=0){
cout<<"0 ";
return 0;
}
convert(Number, base);
cout<<" ";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.