Write an iterative C++ program to prompt the user to enter a nonnega.docx
1. Write an iterative C++ program to prompt the user to enter a
nonnegative integer n and its base b_1, the program then will
prompt the user to enter the new base b_2 to convert and
display the integer n to b_2 expansion For example: The user
enter 11111010111100 b_1 = 2 b_2 = 8 the program will
convert and display 37274
Solution
#include <iostream>
#include <cstring>
#include <cmath>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
int to_dec(char value[], int starting_base);
char* from_dec(int value, int ending_base);
int main() {
char value[30];
int starting_base;
int ending_base;
cout << "This program converts from one base to another, so
long as the bases are" << endl
2. << "between 2 and 16." << endl
<< endl;
input_numbers:
cout << "Enter the number, then starting base, then ending
base:" << endl;
cin >> value >> starting_base >> ending_base;
if (starting_base < 2 || starting_base > 16 || ending_base < 2 ||
ending_base > 16) {
cout << "Invalid base(s). ";
goto input_numbers;
}
for (int i=0; value[i]; i++) value[i] = toupper(value[i]);
cout << "Base " << ending_base << ": " <<
from_dec(to_dec(value, starting_base), ending_base) << endl;
return 0;
}
int to_dec(char value[], int starting_base) {
char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
long int return_value = 0;
unsigned short int digit = 0;
for (short int pos = strlen(value)-1; pos > -1; pos--) {
for (int i=0; i<starting_base; i++) {
if (hex[i] == value[pos]) {