How To Write a C Program To Convert Binary To Decimal Number in C Programming Language ?
Solution For C Program To Convert Binary To Decimal Number:
#include<stdio.h> #include<conio.h> #include<math.h> void bin_dec(long int num) // Function Definition { long int rem,sum=0,power=0; while(num>0) { rem = num%10; num = num/10; sum = sum + rem * pow(2,power); power++; } printf("Decimal number : %d",sum); } //------------------------------------- void main() { long int num; clrscr(); printf("Enter the Binary number (0 and 1): "); scanf("%ld",&num); bin_dec(num); getch(); }Output :Enter the Binary number : 111 Decimal number : 7
Logic of This Program :
In the main function we have accepted the proper binary input i.e suppose we have accepted 111 as binary input.
printf("Enter the Binary number (0 and 1): "); scanf("%ld",&num);
Inside the function while loop gets executed. Sample Dry run for the while loop is shown below -
Iteration | num | rem | sum | power |
---|---|---|---|---|
Before Entering into Loop | 111 | Garbage | 0 | 0 |
After Iteration 1 | 11 | 1 | 1 | 1 |
After Iteration 2 | 1 | 1 | 3 | 2 |
After Iteration 3 | 0 | 1 | 7 | 3 |
Algorithm for Binary to Decimal :
- Accept Number from User
- Divide Number by 10 and Store Remainder in variable rem
- Divide Original Number by 10.
sum = sum + rem * pow(2,power);
Inside the First Iteration power = 0. Power is Incremented in each Iteration.
- Calculate sum using the above formula, calculated sum is nothing but the decimal representation of the given binary number.