Write a C++ program that converts a decimal number to a binary, octal, and hexadecimal equivalents. First, the program will ask to fix a range for the lower and upper limit in which the conversion is required. The lower limit should not be less than 0 and greater than the upper limit. For example, if you enter a negative number or greater than the upper limit, then the program should print a message for the invalid input and will ask you again to enter a decimal number within the range. If you correctly specify the upper and lower limits, then the program will print a table of the binary, octal and hexadecimal equivalents of the decimal numbers in the range of lower limit through upper limit.
#include <iostream>
#include <string>
using namespace std;
string bin(int x) {
string res;
if (x == 0) {
res = "0";
}
else {
while (x > 0) {
res = (x%2 ? "1" : "0") + res;
x /= 2;
}
}
return res;
}
int main() {
int lower, upper;
while (true) {
cout << "Enter lower and upper limit: ";
cin >> lower >> upper;
if (lower >= 0 && lower <= upper) {
break;
}
cout << "Incorrect input, try again" << endl;
}
cout <<"dec\tbin\toct\thex" << endl;
for (int i=lower; i<=upper; i++) {
cout << dec << i << "\t" << bin(i) << oct
<< "\t" << i << "\t" << hex << i << endl;
}
return 0;
}
Comments
Leave a comment