Find Product of 2 Numbers 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)
{
if (a < b)
{
return product(b, a);
}
else if (b != 0)
{
return (a + product(a, b - 1));
}
else
{
return 0;
}
}
Output
Enter two numbers to find their product: 176 340
Product of 176 and 340 is 59840
Print Binary Equivalent of an Integer using Recursion
#include
#include
int binary_conversion(int);
int main()
{
int num, bin;
printf("Enter a decimal number: ");
scanf("%d", &num);
bin = binary_conversion(num);
printf("The binary equivalent of %d is %d\n", num, bin);
}
int binary_conversion(int num)
{
if (num == 0)
{
return 0;
}
else
{
return (num % 2) + 10 * binary_conversion(num / 2);
}
}
}
Output
Enter a decimal number: 10
The binary equivalent of 10 is 1010
Find whether a Number is Prime or Not using Recursion
#include
#include
int primeno(int, int);
int main()
{
int num, check;
printf("Enter a number: ");
scanf("%d", &num);
check = primeno(num, num / 2);
if (check == 1)
{
printf("%d is a prime number\n", num);
}
else
{
printf("%d is not a prime number\n", num);
}
return 0;
}
int primeno(int num, int i)
{
if (i == 1)
{
return 1;
}
else
{
if (num % i == 0)
{
return 0;
}
else
{
return primeno(num, i - 1);
}
}
}
Output
Enter a number: 456
456 is not a prime number
Enter a number: 89
89 is a prime number
Find Sum of N Numbers using Recursion
#include
#include
void display(int);
int main()
{
int num, result;
printf("Enter the Nth number: ");
scanf("%d", &num);
display(num);
return 0;
}
void display(int num)
{
static int i = 1;
if (num == i)
{
printf("%d \n", num);
return;
}
else
{
printf("%d ", i);
i++;
display(num);
}
}
Output
Enter the Nth number: 10
1 2 3 4 5 6 7 8 9 10
Find Reverse of a Number using Recursion
#include
#include
#include
int rev(int, int);
int main()
{
int num, result;
int length = 0, temp;
printf("Enter an integer number to reverse: ");
scanf("%d", &num);
temp = num;
while (temp != 0)
{
length++;
temp = temp / 10;
}
result = rev(num, length);
printf("The reverse of %d is %d.\n", num, result);
return 0;
}
int rev(int num, int len)
{
if (len == 1)
{
return num;
}
else
{
return (((num % 10) * pow(10, len - 1)) + rev(num / 10, --len));
}
}
Output
Enter an integer number to reverse: 1234
The reverse of 1234 is 4321.
No comments:
Post a Comment