Write a C++ program in which write a function convert() that converts a decimal number to a binary, octal, and
hexadecimal equivalents. The function will take two arguments: first argument will be
the number to be converted and second argument will be the base in which this number
is to be converted. Function should return the converted value. You may use strings to
represent converted numbers like “0x3A”, “00101100”, “72” etc.
b. Call convert() function in the main program to produce the following output. It is same
as you made in the previous assignment.
Example output:
Enter upper limit = 20
Enter lower limit = 30
Please enter a value of lower limit between 0 and the upper limit and try again.
Enter lower limit again = 10
............................................................................
Decimal Binary Octal Hexadecimal
#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);
}
Comments
Leave a comment