This is a C program to print binary equivalent of an integer using recursion.
This C program, using recursion, finds the binary equivalent of a decimal number entered by the user.
Decimal numbers are of base 10 while binary numbers are of base 2.
Here is the source code of the C program to display a linked list in reverse. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Print Binary Equivalent of an Integer using Recursion */ #include <stdio.h> int binary_conversion(int); int main() { int num, bin; printf("Enter a decimal number: "); scanf("%d", &num); bin = binary_conversion(num); printf("The binary equivalent of %d is %d\n", num, bin); } int binary_conversion(int num) { if (num == 0) { return 0; } else { return (num % 2) + 10 * binary_conversion(num / 2); } }
In this C program, we are reading a decimal number using ‘num’ variable. Decimal numbers are of base 10, while binary numbers are of base 2. The binary_conversion() function is used to find the binary equivalent of a decimal number entered by the user.
In binary_conversion() function, convert the binary number to its equivalent decimal value. If else condition statement is used to check the value of ‘num’ variable is equal to 0. If the condition is true, execute the statement by returning 0 to the called variable ‘bin’.
Otherwise if the condition is false, execute else statement. Compute the modulus of the value of ‘num’ variable by 2 and add the resulted value to 10. Multiply the resulted value with the value of binary_conversion() function. Divide the value of ‘num’ variable by 2 and pass as an argument and execute the function recursively. Print the Binary equivalent of an integer using recursion.
$ gcc binary_recr.c -o binary_recr $ a.out Enter a decimal number: 10 The binary equivalent of 10 is 1010
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check Computer Science Books
- Check C Books
- Practice Computer Science MCQs
- Practice BCA MCQs
- Watch Advanced C Programming Videos