Q:

C program to decimal to binary using recursion and without using power operator

belongs to collection: Conversion Programs in C

0

In this exercise, we learn how to write a C program to decimal to binary using recursion and without using power operator?. Write a C program to input the decimal number and convert it to a binary number. Convert decimal to binary using recursion and without using a power operator.

Example,

Input: 5
Output: 101
 
 
Input: 9
Output: 1001

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Approach Write a recursive function that takes an argument decimal number ‘n’ and recursively calls itself with the value n/ 2 as the new argument and prints n% 2 after the call. The base condition will be when n= 0, simply print 0 and return out of the function in that case.

#include <stdio.h>
// Recursive function to convert n
// to its binary equivalent
void decimalToBinary(unsigned int n)
{
    // Base case
    if (n == 0)
    {
        printf("0");
        return;
    }
    // Recursive call
    decimalToBinary(n / 2);
    printf("%d",n%2);
}
int main()
{
    //num for decimal number
    unsigned int num;
    printf("Enter decimal number: ");
    scanf("%u", &num);
    //Called function
    decimalToBinary(num);
    return 0;
}

Output:

Enter decimal number: 20
010100

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to decimal to binary number using recurs... >>
<< C Program for Fahrenheit to Kelvin conversion...