C Program to Convert Decimal to Binary using Recursion

This C program converts a decimal number to its binary representation using recursion. It takes a decimal number as input and prints its binary equivalent.

Problem statement

Given a decimal number, we need to convert it to its binary representation using recursion.

C Program to Convert Decimal to Binary using Recursion

#include <stdio.h>

void decimalToBinary(int num)
{
    if (num > 0) {
        decimalToBinary(num / 2);
        printf("%d", num % 2);
    }
}

int main()
{
    int decimalNum;
    printf("Enter a decimal number: ");
    scanf("%d", &decimalNum);
    
    printf("Binary representation: ");
    decimalToBinary(decimalNum);
    
    return 0;
}

How it works

  1. The program prompts the user to enter a decimal number.
  2. The decimal number is stored in the variable decimalNum.
  3. The decimalToBinary function is called with decimalNum as the argument.
  4. Inside the decimalToBinary function:
    • If the number is greater than 0, it calls itself with the quotient num / 2.
    • It then prints the remainder num % 2, which gives the binary digit (0 or 1) at that position.
  5. After all the recursive calls, the binary representation is printed in reverse order.
  6. The main function prints the binary representation obtained by the decimalToBinary function.
  7. The program terminates.

Input/Output

C Program to Convert Decimal to Binary using Recursion

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...