Write a C Program to Convert Binary Numbers to Decimal number using a while loop with an example. This example allows to enter the binary value and uses the while loop to convert binary to decimal.
#include <stdio.h>
int main()
{
int binary, decimal = 0, base = 1, remainder;
printf("Enter the Binary Number = ");
scanf("%d", &binary);
int temp = binary;
while(temp > 0)
{
remainder = temp % 10;
decimal = decimal + remainder * base;
temp = temp / 10;
base = base * 2;
}
printf("The Binary Value = %d\n", binary);
printf("The Decimal Value = %d\n", decimal);
return 0;
}

Binary = 1101
While Loop first Iteration: while(1101 > 0) – True
remainder = 1101 % 10 = 1
decimal = 0 + 1 * 1 = 1
temp = 110
base = 1 * 2 = 2
Second Iteration: while(110 > 0) – True
remainder = 110 % 10 = 0
decimal= 1 + 0 * 2 = 1
temp = 11
base = 2 * 2 = 4
Binary to Decimal Third Iteration: while(11 > 0) – True
remainder = 11 % 10 = 1
decimal= 1 + 1 * 4 = 5
temp = 1
base = 4 * 2 = 8
Fourth Iteration: while(1 > 0) – True
remainder = 1 % 10 = 1
decimal = 5 + 1 * 8 = 13
temp = 0
base = 8 * 2 = 16
Fifth Iteration: while(0 > 0) – False. The compiler exits from the loop and the final value = 13.
C Program to Convert Binary to Decimal number using for loop
#include <stdio.h>
int main()
{
int binary, decimal = 0, base = 1, remainder, temp;
printf("Enter the Binary Number = ");
scanf("%d", &binary);
for(temp = binary; temp > 0; temp = temp / 10)
{
remainder = temp % 10;
decimal = decimal + remainder * base;
base = base * 2;
}
printf("The Binary Value = %d\n", binary);
printf("The Decimal Value = %d\n", decimal);
return 0;
}
Binary to Decimal using for loop output
Enter the Binary Number = 110110
The Binary Value = 110110
The Decimal Value = 54
In this Program, we created a function and used a slightly different approach to Convert Binary to Decimal numbers.
#include <stdio.h>
#include <math.h>
int binaryToDecimal(int binary)
{
int decimal = 0, i = 0, remainder;
while(binary != 0)
{
remainder = binary % 10;
decimal = decimal + (remainder * pow(2, i));
binary = binary / 10;
++i;
}
return decimal;
}
int main()
{
int binary, decimal;
printf("Enter the Binary Number = ");
scanf("%d", &binary);
decimal = binaryToDecimal(binary);
printf("The Binary Value = %d\n", binary);
printf("The Decimal Value = %d\n", decimal);
return 0;
}
Binary to Decimal using Functions output
Enter the Binary Number = 11110101
The Binary Value = 11110101
The Decimal Value = 245