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 finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...