PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Conversion

Program to convert a binary number into decimal number

Input - Output

Input
Enter a Binary number : 1001

Output
Decimal equivalent of given number : 9

Input
Enter a Binary number : 1100

Output
Decimal equivalent of given number : 12

Algorithm

Step 1: START

Step 2: Enter a binary number 'num' as an input.

Step 3: Multiply each digit of num by the power of 2 and store each multiplication.

i.e Power of 2 starts from 0 to n-1 where n is the total number of digits in the num

Step 4: END

CODE


/* Binary to Decimal Conversion */

#include <stdio.h>
#include <math.h>
int main()
{
      int bin,decimal=0,rem,i,j;
      printf(" Enter the binary number : ");
      scanf("%d",&bin);
      for(i=0;bin>0;i++)
    {
        rem=bin%10;
        decimal=decimal+rem*pow(2,i);
        bin/=10;
    }
      printf(" decimal of given number is = %d",decimal);
    return 0;
}


/* Binary to Decimal Conversion */

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
      int bin,decimal=0,rem,i,j;
      cout<<" Enter the binary number : ";
      cin>>bin;
      for(i=0;bin>0;i++)
    {
        rem=bin%10;
        decimal=decimal+rem*pow(2,i);
        bin/=10;
    }
      cout<<" decimal of given number is = "<<decimal;
    return 0;
}

OutPut

Enter a Binary number : 1001

Decimal equivalent of given number : 9