Write a recursive function that prints the binary equivalent of an integer in C program
时间: 2024-05-06 17:17:28 浏览: 10
Here is an example C program that uses a recursive function to print the binary equivalent of an integer:
```c
#include <stdio.h>
void toBinary(int num);
int main() {
int decimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
printf("Binary equivalent: ");
toBinary(decimal);
return 0;
}
void toBinary(int num) {
if (num <= 1) {
printf("%d", num);
return;
}
toBinary(num / 2);
printf("%d", num % 2);
}
```
In this code, the `toBinary()` function is called recursively to print the binary equivalent of the input decimal number. The function takes an integer `num` as input and recursively divides it by 2 until it reaches 1 or 0. At each step, the remainder of the division is printed in reverse order, giving the binary equivalent of the original number.