+ 1
Why does it not return 1?
Hi, so I was learning C++ and recursion confused me because isn't it suppised to return 1 in this example below #include <iostream> using namespace std; int factorialFinder(int x){ if (x==1){ return 1; } else{ return x*factorialFinder(x-1); int main(){ cout << factorialFinder(5); return 0; }
2 Answers
+ 3
It return 5 * the result of findFactorial(4) which is 4 * the result of findFactorial(3) etc...
Anyway, return doesnāt end the entire recursive function with that value, it ends that iteration of it.
So if I made a function:
#include <iostream>
using namespace std;
int func(int a) {
if (a == 0) return 63;
else return func(0) * 2;
}
int main() {
cout << func(0) << endl;
//63
cout << func(4);
//126
}
func(4) returns the double of func(0) because the return in func(0) only returns for that func. Otherwise, since main() is a function, if you called a function with a return value in main(), it would end the program.
+ 2
I am missing two curly (closing) braces in your code, before int main. Like this the code returns 120:
#include <iostream>
using namespace std;
int factorialFinder(int x) {
if (x==1){
return 1;
}
else{
return x*factorialFinder(x-1);
}
}
int main(){
cout << factorialFinder(5);
return 0;
}
It returns recursively 1, 2, 6, 24 and finally 120. That is what you see, the last one.