Contact Learn C
Copy

Program 28:Convert Binary to Decimal

Program 28:
 
#include<stdio.h>
#include<math.h>
main()
{
int dec=0,temp,i,inc=0,binary;
printf("Enter a numer to convert to binary number\n");
scanf("%d",&binary);
temp=binary;
while(temp!=0)
{
i=temp%10;
dec=dec+(i*pow(2,inc));
temp=temp/10;
inc++;
}
printf("Decimal number of %d is %d\n",binary,dec);
}
Explanation:
Convert Binary to Decimal

  1. The program starts with initializing :
    • dec → To store resulting decimal number
    • temp → To store binary temporarily
    • i →used as helping variable
    • binary → To store binary value given by user
    • inc → Used to increment by 1
  2. printf("Enter a numer to convert to binary number\n");
    scanf("%d",&binary);
    Takes input from user and stores in binary which is in turn stored in temp for future reference.Lets take binary=110,so temp=110.
  3. while(temp!=0)
    {
    i=temp%10;
    dec=dec+(i*pow(2,inc));
    temp=temp/10;
    inc++;
    }
    This is the main logic of this program.Lets take binary=110 and took dec=0,inc=0
    • Iteration 1: temp=110 and 110!=0 which is true so the while loop executes
      • i=temp%10 → 110%10 → i=0
      • dec=dec+(i*pow(2,inc)) → 0+(0*2^0)→ dec=0
      • temp=temp/10 → 110/10 → temp=11
      • inc++ → inc=1
      • Final values are:i=0,dec=0,temp=11,inc=1.
    • Iteration 2: temp=11 and 11!=0 which is true so the while loop executes
      • i=temp%10 → 11%10 → i=1
      • dec=dec+(i*pow(2,inc)) → 0+(1*2^1)→ dec=2
      • temp=temp/10 → 11/10 → temp=1
      • inc++ → inc=2
      • Final values are:i=1,dec=2,temp=1,inc=2.
    • Iteration 3: temp=1 and 1!=0 which is true so the while loop executes
      • i=temp%10 → 1%10 → i=1
      • dec=dec+(i*pow(2,inc)) → 2+(1*2^2)→ dec=6
      • temp=temp/10 → 1/10 → temp=0
      • inc++ → inc=3
      • Final values are:i=1,dec=6,temp=0,inc=3.
    • Iteration 4: temp=0 and 0!=0 which is flase so the while loop terminates
    • Final value after execution is dec=6
  4. printf("Decimal number of %d is %d\n",binary,dec);
    Finally we are printing the result of Decimal which is 6


Output:

Convert Binary to Decimal
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide