Recursion

Having trouble understanding when the function recursivePrintStars calls itself again but this time with a slightly different parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void recursivePrintStars(int lines)
{
	int i;

	if (lines > 0)
	{

		for (i = 0; i < lines; i++)
			cout << "*";
		cout << endl;

		// this  self-call to the function makes this function a recursive one!
		recursivePrintStars(lines - 1);

		for (i = 0; i < lines; i++)
			cout << "*";
		cout << endl;
	}
}
The easy way to understand this is to use it. Just write:
1
2
3
4
int main()
{
recursivePrintStars(5);
}
and run it. You will get
1
2
3
4
5
6
7
8
9
10
*****
****
***
**
*
*
**
***
****
*****

Now play a little with your code. Comment out line 13. You will see only the first and the last lines. Or replace the lines-1 with lines -2. Do you see the pattern now? Note that if you increase lines, you should put a stopping condition, otherwise you will crash your program. For example, replace line 5 with
if ((lines > 0)&& (lines<10)), and then you can replace lines-1 with lines+1
Topic archived. No new replies allowed.