Binary to integer


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.
  1. /*
  2.  * C Program to Print Binary Equivalent of an Integer using Recursion
  3.  */
  4. #include <stdio.h>
  5. int binary_conversion(int);
  6. int main()
  7. {
  8.    int num, bin;
  9.    printf("Enter a decimal number: ");
  10.    scanf("%d", &num);
  11.    bin = binary_conversion(num);
  12.    printf("The binary equivalent of %d is %d\n", num, bin);
  13. }
  14. int binary_conversion(int num)
  15. {
  16.     if (num == 0)
  17.     {
  18.         return 0;
  19.     }
  20.     else
  21.     {
  22.         return (num % 2) + 10 * binary_conversion(num / 2);
  23.     }
  24. }
  25. }
advertisements
$ gcc binary_recr.c -o binary_recr
$ a.out
Enter a decimal number: 10
The binary equivalent of 10 is 1010

0 comments:

Post a Comment

Thanks for comments.