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.
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;
}
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.
Output:
Enter decimal number: 20
need an explanation for this answer? contact us directly to get an explanation for this answer010100