## C Program to Convert Binary to Decimal number

## Program to Convert Binary to Decimal number:Number System

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #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 :**

1 2 | Enter the Binary number : 111 Decimal number : 7 |

## Note :

This program is for beginners (not for Experts) that’s why we haven’t provided any Validations while accepting the input. Please provide proper binary input to this program i.e (0 and 1).

## 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.

1 2 | 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.

1 | 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.