Home »
C programs »
C recursion programs
C program to calculate the product of two numbers using recursion
Here, we are going to learn how to calculate the product of two numbers using recursion in C programming language?
Submitted by Nidhi, on July 09, 2021
Problem statement
Here, we will read two integer numbers from the user and then calculate the product of both numbers using a recursive function.
C program to calculate the product of two numbers using recursion
The source code to calculate the product of two numbers using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to calculate the product of two numbers
// using recursion
#include <stdio.h>
int calculateProduct(int num1, int num2)
{
if (num1 < num2) {
return calculateProduct(num2, num1);
}
else if (num2 != 0) {
return (num1 + calculateProduct(num1, num2 - 1));
}
else {
return 0;
}
}
int main()
{
int num1 = 0;
int num2 = 0;
int product = 0;
printf("Enter Num1: ");
scanf("%d", &num1);
printf("Enter Num2: ");
scanf("%d", &num2);
product = calculateProduct(num1, num2);
printf("Product is: %d", product);
return 0;
}
Output
RUN 1:
Enter Num1: 10
Enter Num2: 20
Product is: 200
RUN 2:
Enter Num1: 3
Enter Num2: 8
Product is: 24
RUN 3:
Enter Num1: 121
Enter Num2: 6
Product is: 726
RUN 4:
Enter Num1: 2
Enter Num2: 9
Product is: 18
Explanation
In the above program, we created two functions calculateProduct() and main() function. The calculateProduct() function is a recursive function, which is used to calculate the product of two numbers and return the result to the calling function.
In the main() function, we read two integer numbers from the user and then we calculated the product of both numbers using the calculateProduct() function and printed the result on the console screen.
C Recursion Programs »