C Program to Convert a Number Decimal System to Binary System using Recursion

The following C program using recursion finds a binary equivalent of a decimal number entered by the user. The user has to enter a decimal which has a base 10 and this program evaluates the binary equivalent of that decimal number with base 2.
Here is the source code of the C program to find the binary equivalent of the decimal number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C Program to Convert a Number Decimal System to Binary System using Recursion
  3.  */
  4. #include <stdio.h>
  5.  
  6. int convert(int);
  7.  
  8. int main()
  9. {
  10.     int dec, bin;
  11.  
  12.     printf("Enter a decimal number: ");
  13.     scanf("%d", &dec);
  14.     bin = convert(dec);
  15.     printf("The binary equivalent of %d is %d.\n", dec, bin);
  16.  
  17.     return 0;
  18. }
  19.  
  20. int convert(int dec)
  21. {
  22.     if (dec == 0)
  23.     {
  24.         return 0;
  25.     }
  26.     else
  27.     {
  28.         return (dec % 2 + 10 * convert(dec / 2));
  29.     }
  30. }

$ cc pgm31.c
$ a.out
Enter a decimal number: 10
The binary equivalent of 10 is 1010.

0 comments:

Post a Comment

 
Top