×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to convert a Decimal number to Binary using Recursion

Here, we are going to learn how to convert a Decimal number to Binary using recursion in C programming language?
Submitted by Nidhi, on July 09, 2021

Problem statement

Here, we will read a decimal number from the user and then convert the decimal number to a binary number using recursion.

C program to convert a Decimal number to Binary using Recursion

The source code to convert a decimal number to binary using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to convert decimal number to binary
// using recursion

#include <stdio.h>

unsigned long long int decimalToBinary(int num)
{
    if (num != 0)
        return (num % 2 + 10 * decimalToBinary(num / 2));
    else
        return 0;
}

int main()
{
    int decNum = 0;
    unsigned long long int binNum = 0;

    printf("Enter Decimal Number: ");
    scanf("%d", &decNum);

    binNum = decimalToBinary(decNum);

    printf("Binary Number: %llu", binNum);

    return 0;
}

Output

RUN 1:
Enter Decimal Number: 123
Binary Number: 1111011

RUN 2:
Enter Decimal Number: 10
Binary Number: 1010

RUN 3:
Enter Decimal Number: 12345
Binary Number: 11000000111001

RUN 4:
Enter Decimal Number: 32767
Binary Number: 111111111111111

Explanation

In the above program, we created two functions decimalToBinary() and main() function. The decimalToBinary() function is used to convert the decimal number to a corresponding binary number using recursion.

In the main() function, we read a decimal number from the user and convert the input number from decimal to binary using the decimalToBinary() function and printed the result on the console screen.

C Number System Conversion Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.