Answer to Question #329478 in C++ for Jack

Question #329478

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.

for while and do while loops must be used only once. anything else is not allowed to be used. functions can also be not used.


Example output:

Enter upper limit = 12

Enter lower limit = 30

Invalid.

Enter lower limit again = 10

Further table will be printed .


1
Expert's answer
2022-04-18T08:55:47-0400
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;


string to_string(int n, int base) {
    string str;
    if (n <= 0) {
        return "0";
    }


    while (n > 0) {
        int d = n % base;
        n /= base;
        char ch;
        if (d < 10) {
            ch = '0' + d;
        }
        else {
            ch = 'A' + (d-10);
        }
        str = ch + str;
    }
    return str;
}


int main() {
    int x, lower, upper;


    cout << "Enter upper limit = ";
    cin >> upper;
    if (upper <= 0) {
        cout << "Invalid" << endl;
        cout << "Enter upper limit again = ";
        cin >> upper;
    }


    cout << "Enter lower limit = ";
    cin >> lower;
    if (lower < 0 || lower > upper) {
        cout << "Invalid" << endl;
        cout << "Enter lower limit again = ";
        cin >> lower;
    }


    cout << "decimal       binary    octal   hexadecimal" << endl;
    for (x=lower; x<=upper; x++) {
        cout << setw(7) << x << " "
             << setw(12) << to_string(x, 2) << " "
             << setw(8) << to_string(x, 8) << "          "
             << setw(4) << to_string(x, 16) << 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