We need to write a **C program** to **convert a decimal number into its corresponding binary number**.

**Example:**

1 2 3 4 5 |
Input: 1111 Output: 15 Input: 101 Output: 5 |

Let’s see how this can be implemented?

## Convert Binary to Decimal in C

This is the standard way of converting any binary number into its decimal form. We will do the same as depicted in the above picture i.e mu**ltiple each of the binary digits with the value of 2 raised to the power to its index** ( position from right – 1 ) and sum them up.

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 |
#include <stdio.h> #include <stdlib.h> int main() { int bin, i=0, decimal = 0, lastDigit; printf("Enter a Binary number \n"); scanf("%d",&bin); while(bin != 0){ lastDigit = bin%10; //remainder is the last digit //Add by multiplying the last digit with the 2x decimal = decimal + pow(2,i) * lastDigit; bin = bin/10; //update binary by removing the last digit i = i+1; //power (exponent) } printf("Decimal: %d", decimal); return 0; } |

**Output**

## Convert Binary to Decimal in C using Recursion

The approach in this method is same as the above program but in a recursive way. We need to **extract the last digit from the received binary number** ( only when it is not a single-digit) on each recursive call then we need to **multiply it with its corresponding value of 2 raised to the power its position** in the original binary number from the right and sum it up with next recursive call result.

we need to **eliminate the last digit from binary on next recursive call**.

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 |
#include <stdio.h> #include <stdlib.h> //'i' represent the nth recursive call as well as //nth digit from left, so it can be used as an exponent int binToDec(int bin, int i){ if(bin == 0 || bin == 1) return pow(2,i)*bin; int lastDigit = bin%10; return (pow(2,i) * lastDigit) + binToDec(bin/10, ++i); } int main() { int bin, decimal; printf("Enter a Binary number \n"); scanf("%d",&bin); decimal = binToDec(bin,0); printf("Decimal: %d", decimal); return 0; } |

**Output**

Comment below if you have any doubts or suggestion.