#include<iostream>
usingnamespace std;
//Program to count recursively
//int level;
void count(int val)
{ int level = 0;
//Write some information about the level os recursion
cout<<"Starting count: val == "<<val << ++level;cout <<" val == "<< val<<endl;
//Actual recursion occurs if the condition is true
if(val > 1)
count (val - 1);
//Main task line for function count
cout<<"\t\t\t\t**** Displaying val: " << val <<endl;
cout <<"Leaving count, level val == \n" << level --;
}
int main()
{
int level = 0;
void count(int);
int how_high;
cout <<"Count to what value? ";
cin >> how_high;
level = 0;
count (how_high);
Count to what value? 4
Starting count: val == 41 val == 4
Starting count: val == 31 val == 3
Starting count: val == 21 val == 2
Starting count: val == 11 val == 1
**** Displaying val: 1
Leaving count, level val ==
1 **** Displaying val: 2
Leaving count, level val ==
1 **** Displaying val: 3
Leaving count, level val ==
1 **** Displaying val: 4
Leaving count, level val ==
1
The reason for the second value is (line 10) << ++level. The third: cout <<" val == "<< val<<endl;. Just remove << ++level;cout <<" val == "<< val and you get what you want.
What is level good for anyway? If you want the level of recursion you need to pass level as a second [reference] parameter (within the function you shall not set it to 0):
The disadvantage of this is that it isn't thread-safe.
Another option with default parameters. Notice that the call from main() doesn't specify a level, so it gets the default (1). The recursive calls give the level