Answer to Question #323605 in C++ for Lil

Question #323605

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.

1
Expert's answer
2022-04-04T16:11:27-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS