Suppose you buy a cheap pocket PC and discover that the chip
Suppose you buy a cheap pocket PC and discover that the chip inside can’t do multiplication, but it can do addition. Write a recursive method, mult(), that performas multiplication of x and y by adding x to itself y times. Write a method in the main program to call it and show it works for various values of X and Y. Does the addition take place the method calls itself of when it returns?
Solution
#include <stdio.h>
//method to multiply x and y values
int mult(int x,int y)
{
if(y==1)
return x;
return x+mult(x,y-1);
}
void main()
{
int x,y,result;
printf(\"enter x and y values\");
scanf(\"%d%d\",&x,&y);
result=mult(x,y);
printf(\"product of %d and %d=%d\",x,y,result);
}
output:
sh-4.3$ gcc -o main *.c
sh-4.3$ main
enter x and y values5
5
product of 5 and 5=25
sh-4.3$ gcc -o main *.c
sh-4.3$ main
enter x and y values
6
3
product of 6 and 3=18sh-4.3$
