Thursday, 21 February 2013

C++ program to convert decimal number into binary number

| |

This following program converts a decimal number to a binary number.
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
#include <iostream>
using namespace std;
int main()
{
 long dec,rem,i=1,sum=0;
 cout<<"Enter the decimal to be converted:";
 cin>>dec;
 do
 {
  rem=dec%2;
  sum=sum + (i*rem);
  dec=dec/2;
  i=i*10;
 }while(dec>0);
 cout<<"The binary of the given number is:"<<sum<<endl;
 cin.get();
 cin.get();
 return 0;
}

What happens in the Do While loop:

Step 1. Divide the number in decimal format by 2 and save the remainder in “rem”
Step 2. Place the remainder in the variable sum. We multiply our remainder by “i” so it falls in the right place. i.e, Ones place in 1st time, tens at 2nd and so on.
Step 3. Halve the number in decimal format and save it back to “dec”
Step 4. Multiply “i” by 10 so the next number is placed one place higher in the binary number (i.e, hundreds after tens and thousands after hundreds).
Step 5. Repeat the above steps till decimal number reaches 0

C++ program to convert decimal number into binary number


Related Posts Plugin for WordPress, Blogger...
Powered by Blogger.

Receive All Free Updates Via Facebook.