105k views
0 votes
How do you write a computer program to convert a decimal number into binary, octal, and hexadecimal?

User Barracuda
by
5.9k points

1 Answer

2 votes

Answer:

#include <iostream>

using namespace std;

void hexadecimal(int dec)

{

char hexa[100];// character array to store hexadecimal number.

int i = 0;

while(dec!=0)

{

int digit = 0;

digit = dec % 16;// storing remainder.

if(digit < 10)//condition

{

hexa[i] = digit + 48;//storing digit according to ascii values.

i++;

}

else

{

hexa[i] = digit + 55; //storing respective character according to ascii values..

i++;

}

dec = dec/16;

}

cout<<"The corresponding Hexadecimal number is :- ";

for(int j=i-1; j>=0; j--)// printing in reverse order .

cout << hexa[j];

cout<<endl;

}

void Binary(int dec)

{

int bin[32];// integer array to store binary values.

int i = 0;

while (dec > 0) {

bin[i] = dec % 2;// storing remainder

dec = dec / 2;

i++;

}

cout<<"The corresponding Binary number is :- ";

for (int j = i - 1; j >= 0; j--) // printing in reverse order

cout << bin[j];

cout<<endl;

}

void Octal(int dec)

{

int oct[100];// integer array to store octal values.

int i = 0;

while (dec != 0) {

oct[i] = dec % 8;// storing remainder

dec = dec / 8;

i++;

}

cout<<"The corresponding Octal number is :- ";

for (int j = i - 1; j >= 0; j--) // printing in reverse order

cout << oct[j];

cout<<endl;

}

int main() {

int d,bin,oct,hex;

cout<<"Enter decimal number"<<endl;

cin>>d;//taking input.

Binary(d);

Octal(d);

hexadecimal(d);

return 0;

}

OUTPUT:-

Enter decimal number

10

The corresponding Binary number is :- 1010

The corresponding Octal number is :- 12

The corresponding Hexadecimal number is :- A

Enter decimal number

256

The corresponding Binary number is :- 100000000

The corresponding Octal number is :- 400

The corresponding Hexadecimal number is :- 100

Step-by-step explanation:

I have built 3 function of type void Hexadecimal,Binary,Octal all the functions take decimal integer as argument.They print their respective number after conversion.

So main approach is that :-

1.Take an array to store the digit on dividing.

2.Find the remainder on dividing it by corresponding number (for ex:- if binary divide by 2).

3.Store each remainder in the array.

4.Divide the number until it becomes 0.

5.Print the array in reverse.