Thursday, 27 February 2014

Conversion from Decimal Number to Binary Number - C++ Program Code

So most of you out there know that computers does not use the normal number system, but another one called binary number system, which only has two digits (0 and 1) in it. That's why this program is important.
To understand this, you must know about the normal (manual) method of conversion. Here is a recap.

Consider the decimal number 7. To convert this you must divide the number by 2 repeatedly until the number reduces to 0. The binary equivalent is the remainders wrote in reverse order. Here is the process:


Now we just need to transfer this exact process into program. 

Code:
#include<iostream>
#include "conio.h";
using namespace std;

int main()
{
    int dec, bin[100],i=0,j;
    cout<<"Enter the decimal number : ";
    cin>>dec;
    do
    {
       bin[i]=dec%2;
       i++;
       dec = dec/2;
    }while(dec!=0);
       
    
    cout<<"\nThe binary equivalent is ";
    for(j=i-1;j>=0;j--)
    {
        cout<<bin[j];
    }
    getch();
    return 0;
}

Output:

Working:

The given decimal number is divided repeatedly by 2, and the remainders are stored in an array, and the array is printed in reverse order. Just like the real process! 

Here is the program to convert a binary number to decimal number:

Conversion of Binary Number to Decimal Number - C++ Program Source Code


Happy Coding!
:)




No comments:

Post a Comment

You might also like