Answer to Question #328869 in C++ for okeei

Question #328869

Note: without using library and functions.


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.

Specific grading criteria: In this program you should use all the loops (e.g., while,

do-while and for loop) each of them only one time. The output mentioned below is just

an example; more clear and well- presented output will improve your points.


1
Expert's answer
2022-04-14T15:38:19-0400
#include<iostream>
#include<string>

using namespace std;

int ToBin(int n)
{
	int binary = 0;
	int rem, prod = 1;
	for (;;) 
	{
		if (n == 0)break;
		rem = n % 2;
		binary = binary + (rem*prod);
		n = n / 2;
		prod *= 10;
	}
	return binary;
}


int ToOctal(int n)
{
	int octal = 0;
	int rem, prod = 1;
	while (n != 0)
	{
		rem = n % 8;
		octal = octal + (rem*prod);
		n = n / 8;
		prod *= 10;
	}
	return octal;
}

string ToHex(int n)
{
	string hexal="";
	do
	{
		int temp = n % 16;
		if (temp < 10)
			hexal=char(temp+48)+hexal;
		else
		{
			hexal = char(temp + 55) + hexal;
		}
		n = n / 16;
	} while (n != 0);
	return hexal;
}

int main()
{
	int lowLim, upLim;
	do
	{
		cout << "Please, enter lower limit and upper limit: ";
		cin >> lowLim >> upLim;
		if (lowLim >= 0 && lowLim < upLim)
		{
			cout << "Bin\tOct\tHex\n";
			for (int i = lowLim; i <= upLim; i++)
			{
				cout << ToBin(i)<<"\t" <<ToOctal(i)<<"\t"<<ToHex(i)<< endl;
			}
		}
		else
			cout << "Incorrect input!"<<endl;
	} while (lowLim <= 0 || lowLim >= upLim);
}

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