Contact Learn C
Copy

Program 27:Convert Decimal to Binary

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

Convert Decimal to Binary

  1. The program starts with initializing :
    • dec → To store decimal number
    • temp → To store dec temporarily
    • i,j →used as helping variables
    • binary → To store resulted binary value
  2. printf("Enter a numer to convert to binary number\n");
    scanf("%d",&dec);
    temp=dec;
    Takes input from user and stores in dec which is in turn stored in temp for future reference.Lets take dec=10,so temp=10.
  3. while(temp!=0)
    {
    i=temp%2;
    binary=binary+(i*j);
    temp=temp/2;
    j=j*10;
    }
    This is the main logic of this program.Lets take dec=10
    • Iteration 1: temp=10 and 10!=0 which is true so the while loop executes
      • i=temp%2 → 10%2 → i=0
      • binary=binary+(i*j) → 0+(0*1)→ binary=0
      • temp=temp/2 → 10/2 → temp=5
      • j=j*10 → 1*10 → j=10
      • Final values are:i=0,binary=0,temp=5,j=10.
    • Iteration 2: temp=5 and 5!=0 which is true so the while loop executes
      • i=temp%2 → 5%2 → i=1
      • binary=binary+(i*j) → 0+(1*10)→ binary=10
      • temp=temp/2 → 5/2 → temp=2
      • j=j*10 → 10*10 → j=100
      • Final values are:i=1,binary=10,temp=2,j=100.
    • Iteration 3: temp=2 and 2!=0 which is true so the while loop executes
      • i=temp%2 → 2%2 → i=0
      • binary=binary+(i*j) → 10+(0*100)→ binary=10
      • temp=temp/2 → 2/2 → temp=1
      • j=j*10 → 100*10 → j=1000
      • Final values are:i=0,binary=10,temp=1,j=1000.
    • Iteration 4: temp=1 and 1!=0 which is true so the while loop executes
      • i=temp%2 → 1%2 → i=1
      • binary=binary+(i*j) → 10+(1*1000)→ binary=1010
      • temp=temp/2 → 1/2 → temp=0
      • j=j*10 → 1000*10 → j=10000
      • Final values are:i=1,binary=1010,temp=0,j=10000.
    • Iteration 5: temp=0 and 0!=0 which is false so the while loop terminates
    • printf("Binary number of %d is %d\n",dec,binary);
    • Final Out is printed which is binary=1010


 Output:


Convert Decimal to Binary
Donate

Download App and Learn when ever you want

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