This program converts all the decimal numbers in an array to binary.

To convert a decimal number into binary, we follow the following steps:

Divide the decimal number by 2 and note the remainder

Divide the Quotient repeatedly by 2 and note the remainders till quotient is 0

Write remainder side by side in reverse order to know the binary number

For example 18

18 divide by 2 leaves quotient 9 remainder 0

9 divide by 2 leaves quotient 4 remainder 1

4 divide by 2 leaves quotient 2 remainder 0

2 divide by 2 leaves quotient 1 remainder 0

1 divide by 2 leaves quotient 0 remainder 1

So binary of 18 is 10010

The Program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include<iostream> using namespace std; int main(){ int DecimalArray[] = {1,2,3,4,5,22,555,85,18,741}; //Create an array of decimal numbers. const int ArrayLen = sizeof(DecimalArray)/sizeof(int); //Store the size of the Decimal Array in a constant int BinaryArray [ArrayLen]; //Create an array of the same length for binary nos. for(int i = 0; i<ArrayLen; i++) { int CurrentDec = DecimalArray[i]; //Store current Decimal number in CurrentDec variable int index = 1, rem, CurrentBin = 0; do//Loop to convert the current the current decimal no. to binary. { rem = CurrentDec%2; //Store the 1 or 0 remainder in 'rem' variable CurrentBin = CurrentBin + (index*rem); //Update the Current Binary Variable CurrentDec = CurrentDec/2; index=index*10; }while(CurrentDec>0); BinaryArray[i] = CurrentBin; //Store the current Decimals Binary equivalent in the same position in the Binary array } cout<<"The Decimal numbers and their Binary Equivalents are:\n\n"; cout<<"Decimal Binary \n\n"; //Output both arrays for(int i = 0; i<ArrayLen; i++){ cout<<DecimalArray[i]<<"\t "<<BinaryArray[i]<<endl; } cin.get(); return 0; } |

Output:

The following two tabs change content below.

#### Lalit Mali

Lalit is a technology enthusiast, a programming lover and currently an Android fan.

#### Latest posts by Lalit Mali (see all)

- Rank Pages in a Directory by Occurrence of a Particular Word in them – Java Data Mining - October 16, 2012
- Java Data Mining: Number of occurrences of a word in a file - October 15, 2012
- Calculate factorial of a number using C++ Recursive function - October 14, 2012