int prod(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
else {
return a prod(a, b - 1);
}
}
It looks simple but I can't understand why it works? How does it return the correct product if it eventually returns 0? I'd appreciate if someone could walk me through the process of this, thanks.
CodePudding user response:
Well most peoples will dislike it but ill try to explain it to you.
So lets write random numbers for example a =3 b=4 to be different.
So the program doesn't know how it is for real 3 prod(3,4) just simple and what is he going to do well hes going to call next function like 3 prod(3,3) //because u decrement 1; and again program doesn't really know how it is and will keep calling itself until 3 reach 0 and will return 0 to next function.
I will show u how it looks like now
- a = 3 b=4
3 (3,4) //it checks if b or a ==0
3 (3,3) //it checks if b or a ==0
3 (3,2)//it checks if b or a ==0
3 (3,2)//it checks if b or a ==0
3 (3,1)//it checks if b or a ==0
3 (3,0) //it checks if b or a ==0
and last one ya a==0
So condition is correct so
it return 3 to function which called it in this case return prod 3 (3,1)
called return prod 3 (3,0)
so it will from prod 3 (3,0) to 3 (3,1) and what value it will return?
of course 0
so it will keep returning
3 prod(3,1) ==0 // 0 is returned arleady and program knows this value
3 prod(3,2) == 3 3
3 prod(3,3) ==3 6
3 prod(3,4) ==3 9
so finally u have 12.
CodePudding user response:
Well the function obeys a simple maths rule which is : a*b = a a*(b-1) and a*(b-1) = a a*(b-2) and etc So the function goes through a product by decomposing a*b to a*(b-1) until it reaches the value 0 where it stops.
CodePudding user response:
If b is 0 it returns 0 (because if you multiply something with 0 you get 0).
Is b is positive it returns a prod(a,b-1);
Yes the innermost call prod(a,0) will return 0 the one which called it prod(a,1) will return a and so on until the original prod(a,b) will return a a ... a=a*b
Note that it only works if b is not negative. Also the check if a==0 is irrelevant. (It makes the code a bit faster if a==0 but in this code performance is not priority).