Mar 21, 2014 at 3:52pm UTC
Hello
Why the last value is 3.Can anyone explain to me, please?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
using namespace std;
int fn(int a){
cout << a << "-" ;
if ((a==0) || (a==1))
{cout << a << endl;
return a;}
return fn(a-1)+fn(a-2);
}
int main(){
int a = fn(4);
cout <<a << endl;
return 0;
}
output is : 4-3-2-1-0-1-2-1-0-3
Last edited on Mar 21, 2014 at 4:08pm UTC
Mar 21, 2014 at 4:24pm UTC
I ran this and got slightly different output. But the 3 at the end comes from the result of all the recursive calls to the function that eventually adds 2 (
fn(a-1)
) and 1(
fn(a-2)
) to assign 3 to
a
in the main function. The main function then prints out 3.
4-3-2-1-1
0-0
1-1
2-1-1
0-0
3
Last edited on Mar 21, 2014 at 4:26pm UTC
Mar 21, 2014 at 4:34pm UTC
#include <iostream>
using namespace std;
int fn(int a){
cout << a << "-";
if ((a==0) || (a==1))
return a;
return fn(a-1)+fn(a-2);
}
int main(){
int a = fn(4);
cout <<a << endl;
return 0;
}
This should be the correct version, the first version is used to check the "a"(keep working on it)
Thank you very much.