Friday, 8 September 2017

Recursive Function in C to Convert Decimal number to Binary



Write a program to convert the given decimal number into equivalent binary number using recursion.

Program:
#include <stdio.h>
int dec2bin(int a)
{
               if(a>1)
                      dec2bin(a/2);
               printf("%d\t",a%2);
}
main()
{
               int n;
               printf("enter a number");
               scanf("%d",&n);
               dec2bin(n);
}

Output:


Decimal to Binary Using Loops

#include <stdio.h>
int main()
{
int n,ans=0,p=1,r;
scanf("%d",&n);
while(n>0)
{
r=n%2;
n=n/2;
ans=ans+p*r;
p=p*10;
}
printf("%d",ans);
}

No comments:

Post a Comment