Monday, November 24, 2014

C recursion pro



Convert Binary Code of a Number into its Equivalent Gray’s Code using Recursion

 
#include 
#include   
int bintogray(int);
int main ()
{
int bin, gray;
printf("Enter a binary number: ");
scanf("%d", &bin);
gray = bintogray(bin);
printf("The gray code of %d is %d\n", bin, gray);
return 0;
}
int bintogray(int bin)
{
int a, b, result = 0, i = 0;
if (!bin)
{
return 0;
}
else
{
a = bin % 10;
bin = bin / 10;
b = bin % 10;
if ((a && !b) || (!a && b))
{
return (1 + 10 * bintogray(bin));
}
else
{
return (10 * bintogray(bin));
       }
    }
}
 
Output
 
Enter a binary number:  1011101
The gray code of 1011101 is 1110011

Find Product of 2 Numbers without using Recursion

 
#include 
#include 
int product(int, int);
int main()
{
int a, b, result;
printf("Enter two numbers to find their product: ");
scanf("%d%d", &a, &b);
result = product(a, b);
printf("Product of %d and %d is %d\n", a, b, result);
return 0;
}
int product(int a, int b)
{
int temp = 0;
while (b != 0)
{
temp += a;
b--;
}
return temp;
}

Output
 
Enter two numbers to find their product:  89  458
Product of 89 and 458 is 40762

Convert Binary Code of a Number into its Equivalent Gray’s Code without using Recursion

 
#include 
#include
#include
#include 
int bintogray(int);
int main ()
{
int bin, gray;
printf("Enter a binary number: ");
scanf("%d", &bin);
gray = bintogray(bin);
printf("The gray code of %d is %d\n", bin, gray);
return 0;
}
int bintogray(int bin)
{
int a, b, result = 0, i = 0;
while (bin != 0)
{
a = bin % 10;
bin = bin / 10;
b = bin % 10;
if ((a && !b) || (!a && b))
{
result = result + pow(10, i);
}
i++;
}
return result;
}

Output
 
Enter a binary number: 1111001010
The gray code of 1111001010 is 1000101111

Convert a Number Decimal System to Binary System using Recursion

 
#include 
#include   
int convert(int);
int main()
{
int dec, bin;
printf("Enter a decimal number: ");
scanf("%d", &dec);
bin = convert(dec);
printf("The binary equivalent of %d is %d.\n", dec, bin);
return 0;
}
int convert(int dec)
{
if (dec == 0)
{
return 0;
}
else
{
return (dec % 2 + 10 * convert(dec / 2));
}
}
 
Output
 
Enter a decimal number: 10
The binary equivalent of 10 is 1010.

No comments:

Post a Comment