When calling the function f4 how is the function returning 6? i really cant figure out how the function operates shouldnt it just return 1? because of (n-1)
#include <iostream>
#include<cmath>
#include<fstream>
using namespace std;
int x = 3;
void f1(int, int &);
int f4(int);
int main()
{
int x = 5; int y = 10;
f1(x, y);
cout << x << "\t" << y << endl;
x = 15; y = 20;
f1(x++, x);
cout << x << "\t" << y << endl;
x = 3;
cout << f4(x) << endl;
system("pause");
return 0;
}
void f1(int a, int &b)
{
a *= 2; b += x;
cout << a << "\t" << b << endl;
}
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
The f4
function is recursive. This calling with a number other than 1 or 0 will make it recurse. You call it with 3, so the compiler (simplified) sees
f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6