# Functions

This is a discussion on Functions within the C++ Programming forums, part of the General Programming Boards category; Hi I have this small program and I have tried to know its outcome but I couldn't understand how the ...

1. ## Functions

Hi I have this small program and I have tried to know its outcome but I couldn't understand how the digit 6 is printed out, all the others I understand.

Code:
```#include <iostream>
using namespace std;
int global = 2;
int rek(intpar) {
cout << par;
global = global + par;
if (par < 7)
return rek(par*2)+2;
else
return 0;
}
int main()
{
cout << rek(1) << global;
return 0;
}```
OK, here is how I understand it. Function rek(1) gets called in main(), and we go to function rek(int par) above. From there, we pass 1 to the function which prints it out and adds it to the global value. Condition is checked which is true and function rek(par*2) is called, which goes back to the function rek(int par) and the int value now is 2, this keeps on going until int par is 8, at which point the condition is false, all the while adding our new int par value to the global value. Now from here I am stuck. From here, if I go to main, according to my understanding, the function should print 1248, which are the values of int par and finally 16 which is the value of global. These are the values returned by the functions, we print this out, and it is over. Or so I thought until I saw the values printed out were 1248616 and not 124816. Now I need help in figuring out where on earth has this 6 come from. Thanks in advance.

2. Before coming to us, you should have done something like this to see where each number is actually coming from:

Code:
```#include <iostream>
using namespace std;

int global = 2;

int rek(int par)
{
cout << "par passed into rek: " << par << endl;
global = global + par;

if (par < 7)
return rek(par * 2) + 2;
else
return 0;
}

int main()
{
cout << "value returned by rek: " << rek(1) << endl;
cout << "global: " << global << endl;

return 0;
}```
Which has output:

Code:
```par passed into rek: 1
par passed into rek: 2
par passed into rek: 4
par passed into rek: 8
value returned by rek: 6
global: 17```
So that 6 is the value returned by rek. We can work this out by hand. We know
rek(1) = rek(2) + 2
rek(2) = rek(4) + 2
rek(4) = rek(8) + 2
rek(8) = 0

So substituting back down:
rek(4) = rek(8) + 2 = 0 + 2 = 2
rek(2) = rek(4) + 2 = 2 + 2 = 4
rek(1) = rek(2) + 2 = 4 + 2 = 6

3. Thank you. I now understand it well.