C program to print binary equivalent of an integer using recursion

C program to print binary equivalent of an integer using recursion


Output:

Enter a number to find its binary equivalent:

35
The binary equivalent of 35 is:100011

Implementation:


/* Decimal numbers are also called as base-10 numbers
   because, decimal numbers are 0,1,2,3,4,5,6,7,8,9
   which is 10 numbers in total.
   
   Binary number is called as base-2
   as, binary numbers are 0 & 1
   
   To convert decimal number into a binary number:
     1. find the remainder of the number
     2. divide the number by 2 & store the result in the same number
     3. repeat steps 1 & 2 until the number becomes zero
     4. now reverse of the remainders would give us binary form of that decimal number
    for example:
     If the given number is 35
     Taking LCM:
      2|35
       ---      ^
      2|17 - 1  | 
       ---      |
      2|8  - 1  |
       ---      |
      2|4  - 0  |Gives you the binary form of 35
       ---      |which is 100011
      2|2  - 0  |   
       ---      |  
      2|1  - 0  | 
       ---      |
      2|0  - 1  |
    */
#include <stdio.h>

/* Recursion function to print the binary form of decimal number entered by user 
   */

void findbinary(int n) // getting the number here
{
 /* checking whether the number reached 0
    If so, return the control to the function called 
    */
 if(n==0)
  return;
 
 /* until n reaches zero,
    keep on dividing the number by 2 &
    recursively call the same function using the resultant value from dividing the number by 2
    */
 findbinary(n/2);
 
 /* After the last recursive call breaks, find the remainder of the number 
    &
    print the remainder of the number in that current recursive function call
    */
 /* this gives you the binary of the decimal number */
 printf("%d",n%2);
}

int main(void) {
 int n;
 printf("Enter a number to find its binary equivalent:\n");
 scanf("%d",&n);
 
 /* function call to find & print the binary of the number entered by the user
    using recursive function 
    */
 printf("The binary equivalent of %d is:",n);
 findbinary(n);
 
 return 0;
}