C Program to convert binary to decimal number

In this c program, we have to convert the binary numbers into decimal numbers. Changing over a binary number into a decimal utilizing the c program is extremely basic.

What is a binary number?

A binary number is a number that is spoken to by just zeros and ones. Binary numbers are spoken to by subscript 2 and decimals spoke to by subscript 10.Example:1001,10010,001 .

For converting binary numbers to decimal we are using a while loop. The logic of this program is first to read the binary number from the user and by using a while loop check num>0 then calculate the following:

rem = num 

dec = dec + rem * base

num = num / 10 

base = base * 2.

After that display the binary numbers as dnum and decimal equivalent as dec using printf.

What is the syntax of the while loop?



while (testExpression)
   {
        // codes inside the body of a while
    }

While loop evaluates the test expression. If the test expression is true, code inside while loop is executed and the test expression is evaluated again. This process continues until the test expression becomes false. When the test expression is false, while loop is terminated.

 

ALGORITHM

STEP 1:Include the header files to use the built-in header files into the C program.

STEP 2: Declare the integer variables num,bnum,dec,base,rem.

STEP 3:Read the binary number into num.

STEP 4: Assign bnum=num.

STEP 5:By using a while loop with the condition num>0 do step 6.

STEP 6: rem=num,dec=dec+rem*base,num=num/10 and base=base*2.

STEP 7:Display the binary number as bnum and decimal equivalent as dec.

 

C Source Code

                                          #include <stdio.h>

void main() {
  int num, bnum, dec = 0, base = 1, rem;
  printf("Enter the binary number(1s and 0s)\n");
  scanf("%d", & num); /*Enter maximum five digits or use long int*/
  bnum = num;
  while (num > 0) {
    rem = num%10;
    dec = dec + rem * base;
    num = num / 10;
    base = base * 2;
  }
  printf("The Binary number is = %d\n", bnum);
  printf("Its decimal equivalent is =%d\n", dec);
} /* End  */
                                      

OUTPUT

Enter the binary number(1s and 0s)
1010
The Binary number is = 1010
Its decimal equivalent is =10