Before I go straight into pseudocode and actual code in C, I just want to explain what are we doing here. So we can multiply a number with another number. Nothing special right? But how can we do it recursively?
Have a look at the following example:
Contents
The approach and Example:
1) 5*1=5
2)1*5=5
So, if any of the numbers is 1, then the product is the other number. That is the basic case.
3)But if neither of the numbers is 1, then we basically add the first number each time, by reducing the value of the second number by 1:
Example: 5*4 can be written as:
5+(5*(4-1))
=5+(5*3)
=5+5+(5*(3-1))
=5+5(5*2)
=5+5+5+(5*(2-1))
=5+5+5+(5*1) //From the first and second example, anything multiplied by the 1 is itself.
=5+5+5+5=20
PsuedoCode for multiplication of two numbers using recursion:
Let x and y be the two numbers whose product is to be calculated then.
product(x,y)
{
if(x==1)
{
return(y);
}
else if(y==1){
return(x);
}
else
{
return(x+product(x,y-1));
}
}
Code in C:
#include<stdio.h>
#include<conio.h>
int product(int,int); /*recursive function defined where we will pass two interger*/
int main()
{
int a, b; /*to store the values */
int p; /*to store product */
printf("Enter the two numbers to know the product recursively: ");
scanf("%d%d",&a,&b);
p=product(a,b); /*recusive function call*/
printf("\nThe product of numbers %d and %d is: %d",a,b,p);
getch();
return(0);
}
int product(int x,int y) /*recusive function where we will do actual calculation*/
{
if(x==1)
{
return(y);
}
else if(y==1){
return(x);
}
else
{
return(x+product(x,y-1));
}
}
Output:
Do comment if you are confused in any steps.
Also Read: Recursive program to calculate the power of the base