Pages

Thursday 10 December 2015

Decimal to binary conversion using C++



Decimal System: It is also called base $10$ system or Denary system. It refer to any number written in decimal notation format.

Binary System: It is also called base $2$ system. It uses two different symbols $0$ or $1$. 


Algorithm:
  1. Divide the decimal number by $2$. Consider the division operation as an integer division.
  2. Note down the remainder (either $0$ or $1$).
  3. Divide the result again by $2$ and again consider the division as an integer division.
  4. Repeat step $2$ and $3$ until result is $0$.
  5. The binary value is the digit sequence of the remainders from the last to first.






#include "iostream"

using namespace std;

int main()
{
  int n,d,a, c, k;

  cout<<"Enter a decimal number :";
  cin>>d;
  n=d;
  cout<<"Binary equivalent of the given number : ";

 for( a=1;n!=0;a++)

  {
     n=n/2;

  }

a=a-2;
  for (c = a; c >= 0; c--)
  {
    k = d >> c;

    if (k & 1)
      cout<<"1";
    else
      cout<<"0";
  }



  return 0;
}
INPUT:       Enter a decimal number : 17
OUTPUT:   Binary equivalent of the given number : 10001


No comments:

Post a Comment