Reputation: 11
#include <cstdlib>
#include <iostream>
using namespace std;
int myFunction(int n)
{
int x;
if (n==1 || n==2)
x = 1;
else
x = myFunction(n-2) + myFunction(n-1);
return x;
}
int main(int argc, char *argv[])
{
int n,a;
n = 7;
a = myFunction(n);
cout << "x is: " << a;
system("PAUSE");
return EXIT_SUCCESS;
}
The output to this is "x is: 13". How do I get x = 13 when I do n = 7? It seems that the function repeats some number of times until x=1.
Upvotes: 0
Views: 90
Reputation: 11769
I will walk you through it for a simpler example where the function is 4, but the overall concept is the same for 7 as well.
First call: myFunction(4)
and inside the function n = 4
.
Since n
does not equal 1 or 2, we skip to the else:
x = myFunction(3) + myFunction(2);
x = myFunction(1) + myFunction(2) + 1; // If there is a 1, that means
// that we went to the if
// clause, not the else, since
// n was either 1 or 2
x = 1 + 1 + 1;
x = 3;
This concept is called recursion and can be very useful at times. Your function currently calculates the nth fibonacci number.
On a side note, you should read why using system("PAUSE");
is a bad idea.
Upvotes: 1