Introduction
In the binary numbering system, each digit (bit) represents a power of 2. The rightmost bit is the least significant bit (2^0), and each bit to the left represents an increasing power of 2. To convert a binary number to decimal, we can use recursion, breaking down the problem into smaller subproblems.
#include <stdio.h>
int binaryToDecimal(int binary) {
// Base case: if binary is 0, return 0
if (binary == 0) {
return 0;
}
// Recursive case: extract the last digit and add to the result of the rest
return (binary % 10) + 2 * binaryToDecimal(binary / 10);
}
int main() {
int binary;
printf("Enter a binary number: ");
scanf("%d", &binary);
int decimal = binaryToDecimal(binary);
printf("Decimal equivalent: %d\n", decimal);
return 0;
}
Explanation
- Function Definition:
- The function
binaryToDecimal
takes an integerbinary
as input. - Base Case: If
binary
is 0, it returns 0, which stops the recursion. - Recursive Case:
- The last digit of the binary number is obtained using
binary % 10
. - The recursive call
binaryToDecimal(binary / 10)
reduces the binary number by one digit. - The last digit is then multiplied by 2 raised to its position (which is effectively managed by the recursive structure).
- The last digit of the binary number is obtained using
- The function
- Main Function:
- It prompts the user to input a binary number.
- It calls
binaryToDecimal
and prints the resulting decimal value.
Input:
Enter a binary number: 1011
Output:
Decimal equivalent: 11
Conclusion
This C program effectively demonstrates the use of recursion to convert a binary number to its decimal equivalent. The recursive approach simplifies the problem by breaking it down into manageable parts, making it easier to understand the conversion process. This method is efficient for small binary numbers but may not be the best choice for very large numbers due to potential stack overflow issues with deep recursion.