a. 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. Lower limit must be smaller than upper limit.
b. Call convert() function in the main program to produce the following output.
Example output:
Enter upper limit = 20
Enter lower limit = 10
Decimal Binary Octal Hexadecimal
10 00001010 12 0xA
11 00001011 13 0xB
12 00001100 14 oxC
13 00001101 15 0xD
14 00001110 16 0xE
15 00001111 17 0xF
16 00010000 20 0x10
17 00010001 21 0x11
18 00010010 22 0x12
19 00010011 23 0x13
20 00010100 24 0x14
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int decToBinary(int n)
{
for (int i = 8; i >= 0; i--) {
int k = n >> i;
if (k & 1)
cout << "1";
else
cout << "0";
}
cout << "\t";
}
string intToOctal(int n)
{
stringstream st;
st << oct << n;
return st.str();
}
void decToHexa(int n)
{
char hexaDeciNum[100];
int i = 0;
while (n != 0) {
int temp = 0;
temp = n % 16;
if (temp < 10) {
hexaDeciNum[i] = temp + 48;
i++;
}
else {
hexaDeciNum[i] = temp + 55;
i++;
}
n = n / 16;
}
for (int j = i - 1; j >= 0; j--)
cout << hexaDeciNum[j];
}
void convert(int i){
cout << i << "\t";
decToBinary(i);
cout << intToOctal(i) << "\t" << "0x";
decToHexa(i);
cout << "\n";
}
int main()
{
int upper, lower;
cout << "Enter upper limit = ";
cin >> upper;
cout << "Enter lower limit = ";
cin >> lower;
if (upper > lower){
for (int i = lower; i <= upper; i++) {
convert(i);
}
}
else{
cout << "You enter incorrect number. Try again.";
}
return 0;
}
Comments
Leave a comment