Print in Binary
Completed
Write a recursive void print_binary(int n) that prints the binary digits most significant first. Print the binary form of each input number.
Input
n, then n non-negative integers.
Output
n lines.
Example
Input
3 5 0 255
Output
101 0 11111111
Editor
C
Hints
Print the higher digits (n / 2) first, then the last digit (n % 2).
Solution explanation
Recursing before printing reverses the order of the digits for free.
Show solution
#include <stdio.h>
void print_binary(int n) {
if (n >= 2) print_binary(n / 2);
printf("%d", n % 2);
}
int main() {
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
print_binary(x);
printf("\n");
}
return 0;
}