C Program to Convert Decimal to Binary with Output
num % 2 to get bits and num /= 2 to reduce the number.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int num, binary[32], i = 0; printf("Enter a decimal number: "); scanf("%d", &num); if (num == 0) { printf("Binary representation: 0\n"); return 0; } while (num > 0) { binary[i] = num % 2; num = num / 2; i++; } printf("Binary representation: "); for (int j = i - 1; j >= 0; j--) { printf("%d", binary[j]); } printf("\n"); return 0; }
Dry Run
Let's trace the input 10 through the code
Initial input
num = 10, binary array empty, i = 0
First iteration
num % 2 = 0, store 0 in binary[0], num = 10 / 2 = 5, i = 1
Second iteration
num % 2 = 1, store 1 in binary[1], num = 5 / 2 = 2, i = 2
Third iteration
num % 2 = 0, store 0 in binary[2], num = 2 / 2 = 1, i = 3
Fourth iteration
num % 2 = 1, store 1 in binary[3], num = 1 / 2 = 0, i = 4
Print binary
Print binary array in reverse: binary[3]=1, binary[2]=0, binary[1]=1, binary[0]=0
| Iteration | num | num % 2 (remainder) | binary array | i |
|---|---|---|---|---|
| 1 | 10 | 0 | [0] | 1 |
| 2 | 5 | 1 | [0,1] | 2 |
| 3 | 2 | 0 | [0,1,0] | 3 |
| 4 | 1 | 1 | [0,1,0,1] | 4 |
Why This Works
Step 1: Divide and get remainder
Each division by 2 gives a remainder of 0 or 1, which is a binary digit.
Step 2: Store remainders
Store each remainder in an array to keep track of the binary digits.
Step 3: Print in reverse
Binary digits are collected from least significant to most significant bit, so print the array backwards.
Alternative Approaches
#include <stdio.h> void printBinary(int num) { if (num > 1) { printBinary(num / 2); } printf("%d", num % 2); } int main() { int num; printf("Enter a decimal number: "); scanf("%d", &num); if (num == 0) { printf("Binary representation: 0\n"); } else { printf("Binary representation: "); printBinary(num); printf("\n"); } return 0; }
#include <stdio.h> int main() { unsigned int num, mask = 1 << 31; int started = 0; printf("Enter a decimal number: "); scanf("%u", &num); printf("Binary representation: "); for (int i = 0; i < 32; i++) { if (num & mask) { printf("1"); started = 1; } else if (started) { printf("0"); } mask >>= 1; } if (!started) printf("0"); printf("\n"); return 0; }
Complexity: O(log n) time, O(log n) space
Time Complexity
The loop runs once for each binary digit, which is proportional to log base 2 of the number.
Space Complexity
An array stores each bit, so space used is proportional to the number of bits (log n).
Which Approach is Fastest?
Bitwise method is fastest and uses constant space, recursion uses call stack, and array method is easiest to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Array with division | O(log n) | O(log n) | Beginners, clarity |
| Recursion | O(log n) | O(log n) (call stack) | Elegant code, moderate complexity |
| Bitwise operators | O(1) per bit (O(log n)) | O(1) | Performance and low memory |