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.
Learn More :
C Program
- Using Bash to input stuff into c program
- Difficult C Programming Questions
- Write a c program to find largest among three numbers using binary minus operator three numbers using binary minus operator
- PRINTING ASCII VALUE USING C PROGRAM
- MULTIPLICATION OF TWO MATRICES USING C PROGRAM
- FIND OUT SUM OF DIAGONAL ELEMENTS OF A MATRIX USING
- Write A C Program To Find Out Transport Of A Matrix
- Factorial of 100 in C Program
- Multiplication of large numbers in c
- Division of Large Numbers in C Program
- BINARY SEARCH USING C PROGRAM
- BINARY SEARCH THROUGH RECURSION USING C PROGRAM
- FIND FACTORIAL OF A NUMBER USING RECURSION IN C PROGRAM
- FIND GCD OF A NUMBER USING RECURSION IN C PROGRAM
- FIND SUM OF DIGITS OF A NUMBER USING RECURSION USING C PROGRAM
- FIND POWER OF A NUMBER USING RECURSION USING C PROGRAM
- REVERSE A NUMBER USING RECURSION IN C PROGRAM
- SWAP TWO VARIABLES WITHOUT USING THIRD USING C PROGRAM VARIABLE
- Write A C Program For Swapping Of Two Arrays
- SWAPPING OF STRINGS USING C PROGRAM
- CONVERSION FROM DECIMAL TO OCTAL USING C PROGRAM
- CONVERSION FROM DECIMAL TO OCTAL USING C PROGRAM
- CONVERSION OF DECIMAL TO BINARY USING C PROGRAM
- CONVERSION OF FAHRENHEIT TO CENTIGRADE USING C PROGRAM
- C or C++ Program To Find Bonus Amount