#include <iostream>
usingnamespace std;
int factorialFinder(int x){
if (x==1){
return 1;
}else{
return x*factorialFinder(x-1);
}
}
int main()
{
cout << factorialFinder (5) << endl;
}
I was under the impression the return gives a value to the function, but if it gives a value then this should print out "1". Instead this prints out "120". I thought this was kind of weird so I put 'return 2;' inside the if (x==1) brackets. It printed out '240'!
In the else bracket I put 'return x+factorialFinder (x-1);' with with the same 'if (x==1){return 1}' and I got 15. When I put 'return 2' I get 16. When I put 'return -2" I get 12. And when I put 'return x-factorialFinder(x-1);' and put 'return 2' I get 4 (still adds on 2).
My new assumption is that an 'int' function already has a value of 1 and return multiplies it by default with a number you give it like:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int example(){
return 22;
}
int main()
{
cout << example();
}
and you get 22. But as with most of my 'assumptions' it's usually wrong. Can someone help clarify this for me?
I'm still confused, but I'm not confused about the else statement part. I'm confused about the 'return 1' part in inside the if statement.
Here's my understanding.
1. The computer goes to "factorialFinder (5)".
2. The value of 5 goes to factorialFinder(int x). Since 5 is not equal to 1 it goes to the else statement.
3. It will do what you say until it reaches 1 (5*(5-1), 20*(4-1), 60*(3-1), 120*(2-1))
**4. (the part I'm having the problem with) When x finally does equal to 1 it will go to the if statement and return 1, as in overwrite factorialFinder () with a value of 1
5. It then prints out "1"
I know this is wrong because it prints out 120.. My assumption is that return multiplies the value with the number you give it instead of giving the function the value of 1. Is this true?
I know this is wrong because it prints out 120.. My assumption is that return multiplies the value with the number you give it instead of giving the function the value of 1. Is this true?
No. The function multiplies the value returned on line 9, then it returns the resulting value.
What you have here is a recursive function; which returns a factorial number. So when "5" is put in, it would return 120 because the function does the following:
5*4*3*2*1
Because when x != 1, it would return the function again using a x-1 as the perimeter. Once x does equal 1, it would return the 1 which would be at the end of all values being multiplied.
What you have here is a recursive function; which returns a factorial number. So when "5" is put in, it would return 120 because the function does the following:
5*4*3*2*1
Because when x != 1, it would return the function again using a x-1 as the perimeter. Once x does equal 1, it would return the 1 which would be at the end of all values being multiplied.