Wednesday, August 24, 2011

Decimal to binary conversion using recursive function


In this program a decimal number will be entered by the user and it will be converted in it’s equivalent binary number. The codes of the program is given below:

#include< stdio.h>
int i=0;
int arr[20];
void rec(int n)
{
 int c= n%2;
 arr[i++]=c;
 n=n/2;
 if(n==1)
 {
 arr[i++]=n;
 return;
 }
 rec(n);
 }
  void main()
   {
   int j,n;
   clrscr();
   printf("\nEnter the number:");
   scanf("%d",&n);
   rec(n);
   printf("\nThe binary equivalent is :");
   for(j=0;j< i;j++)
   printf("%d",arr[j]);
   getch();
   }

In this program of converting decimal number in its’ equivalent binary number, the function ‘rec ()’ is used for converting and this function is called recursively. The one dimensional array and it’s index variable are declared as external variables. The one dimensional array will hold the binary digits. 

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner