...
5 * 4
int result=0;
int n=5;
int m=4;
for (int i=0; i<m; i++)
{
result+=n;
}
m n .
... ...
int multiply(int n, int m)
{
if (n > 0 && m > 0)
return rec_multiply(n,m);
else
return 0;
}
int rec_multiply(int n, int m)
{
return (m==0 ? 0 : multiply(n, m-1))) + n;
}
which calls itself mtime, adding neach time. The recursion must keep track of the exit condition or may cause serious problems of an infinite loop. An additional method is to catch 0 entries, and 0 * - 0.
In recursion, you call a method with n = 5, m = 4. It calls itself, each time decreasing the second number by 1. If it reaches 0, it simply returns 5, otherwise it returns another call to itself +5.
source
share