Function decimalToBinary – CTS PATTERN
Fix the logical error in the decimalToBinary function so it correctly prints the binary representation of a given integer.
Understand the Problem
Problem Statement
Fix all logical errors in the given code. The function decimalToBinary(int N) accepts an integer N as input and is supposed to print the binary representation of N. The function compiles successfully but fails to produce the correct output due to a logical error. Debug the program to make it work correctly.
Constraints
- Input integer N must be greater than 0 (N > 0)
- The function should recursively convert the decimal number to binary
- Output should be the binary representation printed directly
- No additional libraries or main function required
Examples
5101The binary representation of decimal 5 is 101. The recursive calls work as: decimalToBinary(5) → decimalToBinary(2) → decimalToBinary(1) → decimalToBinary(0). On return: print 1%2=1, 2%2=0, 5%2=1, resulting in 101.
81000The binary representation of decimal 8 is 1000. The recursive calls work as: decimalToBinary(8) → decimalToBinary(4) → decimalToBinary(2) → decimalToBinary(1) → decimalToBinary(0). On return: print 1%2=1, 2%2=0, 4%2=0, 8%2=0, resulting in 1000.
Solution
void decimalToBinary(int N){
if(N>0){
decimalToBinary(N/2);
printf("%d",N%2);
}
}The original code had a return 0; statement at the end, which is incorrect since the function is declared as void. The corrected version:
- Checks if N > 0 (base case)
- Recursively calls decimalToBinary(N/2) to process the higher bits
- Prints N%2 to output the current bit
- Does not return any value since it's a void function
The recursive approach naturally handles the bit ordering by printing remainders on the way back up the call stack.