Write a C program to find the product of two numbers using recursion.
#include <stdio.h>
/* product of two number using recursion */
void product(int *val1, int *val2, int temp, int sign) {
if (*val2 <= 1) {
printf("%d\n", ((*val1) * sign));
return;
}
/* val2 time val1 is the product value */
*val1 = *val1 + temp;
*val2 = *val2 - 1;
/* finding product using recursion */
product(val1, val2, temp, sign);
return;
}
int main() {
int val1, val2, temp, sign = 1;
/* get the first input from the user */
printf("Enter your first input:");
scanf("%d", &val1);
/* get the second input from the user */
printf("Enter your second input:");
scanf("%d", &val2);
/* product of two number using recursion */
void product(int *val1, int *val2, int temp, int sign) {
if (*val2 <= 1) {
printf("%d\n", ((*val1) * sign));
return;
}
/* val2 time val1 is the product value */
*val1 = *val1 + temp;
*val2 = *val2 - 1;
/* finding product using recursion */
product(val1, val2, temp, sign);
return;
}
int main() {
int val1, val2, temp, sign = 1;
/* get the first input from the user */
printf("Enter your first input:");
scanf("%d", &val1);
/* get the second input from the user */
printf("Enter your second input:");
scanf("%d", &val2);
/* if any one of the input is negative, output is also -ve */
if ((val1 < 0 && val2 > 0) ||
(val1 > 0 && val2 < 0)) {
sign = -1;
} else if (val1 == 0 || val2 == 0) {
/* if any of the i/p is 0, the o/p is also 0 */
printf("Product of %d and %d is 0\n", val1, val2);
return 0;
}
printf("Product of %d and %d is ", val1, val2);
/* finding the absolute values of both the inputs */
val1 = abs(val1);
val2 = abs(val2);
temp = val1;
/* find product of two numbers using recursion */
product(&val1, &val2, temp, sign);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:20
Enter your second input:40
Product of 20 and 40 is 800
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:0
Enter your second input:40
Product of 0 and 40 is 0
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:10
Enter your second input:1
Product of 10 and 1 is 10
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:10
Enter your second input:-1
Product of 10 and -1 is -10
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:-10
Enter your second input:-1
Product of -10 and -1 is 10
Enter your first input:20
Enter your second input:40
Product of 20 and 40 is 800
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:0
Enter your second input:40
Product of 0 and 40 is 0
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:10
Enter your second input:1
Product of 10 and 1 is 10
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:10
Enter your second input:-1
Product of 10 and -1 is -10
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:-10
Enter your second input:-1
Product of -10 and -1 is 10
No comments:
Post a Comment