Write a C program that prompts the user to enter a hexadecim
Write a C++ program that prompts the user to enter a hexadecimal digit or an integer between 0-15 and display its corresponding decimal number or hex decimal number. The program must first ask the user to choose what kind of conversion and then ask the user to enter a number to convert. ( Include comments )
Solution
// C++ code
 #include <iostream>
 #include <fstream>
 #include <cctype>
 #include <cstring>
 #include <stdlib.h> /* srand, rand */
 #include <iomanip>
 #include <limits.h>
 #include <cmath>
 #include <algorithm>
 #include <vector>
 #include <stack>
using namespace std;
 int getvalue(char ch)
 {
 if (ch >= \'0\' && ch <= \'9\')
 return (int)ch - \'0\';
 else
 return (int)ch - \'A\' + 10;
 }
 
 void toHexaDecimal(int decimalNumber)
 {
 if (decimalNumber == 0)
 return;
int remainder = decimalNumber % 16;
 decimalNumber /= 16;
 toHexaDecimal(decimalNumber);
  
 if (remainder > 9)
 cout << (char)(remainder - 10 + \'A\');
 else
 cout << remainder;
 }
int toDecimal(string s)
 {
 int l = s.length();
 int power = 1;
 int decimalNumber = 0;
for (int i = l - 1; i >= 0; i--)
 {
if (getvalue(s[i]) >= 16)
 {
 cout << \"Invalid Number\ \";
 return -1;
 }
 
 decimalNumber += getvalue(s[i]) * power;
 power = power * 16;
 }
 
 return decimalNumber;
 }
int main()
 {
 int choice;
 string s;
 int number;
while(true)
 {
 cout << \"\ 1. Hex to Decimal\ 2. Decimal to Hex\ 3. Quit\ Enter your choice: \";
 cin >> choice;
if(choice == 1)
 {
 cout << \"Enter Hex: \";
 cin >> s;
 cout << \"Decimal: \" << toDecimal(s) << endl;
 }
else if(choice == 2)
 {
 cout << \"Enter decimal: \";
 cin >> number;
cout << \"Hex: \";
 toHexaDecimal(number);
 cout << endl;
}
 else if(choice == 3)
 break;
 else
 cout << \"Invalid Input\ \";
 }
return 0;
 }
 /*
 output:
1. Hex to Decimal
 2. Decimal to Hex
 3. Quit
 Enter your choice: 1
 Enter Hex: 11A
 Decimal: 282
1. Hex to Decimal
 2. Decimal to Hex
 3. Quit
 Enter your choice: 2
 Enter decimal: 282
 Hex: 11A
1. Hex to Decimal
 2. Decimal to Hex
 3. Quit
 Enter your choice: 3
 */



