Tracing recursion better

Hi everyone. I'm currently learning recursion in college right now (not asking to help solve hw) and I have an assignment that I've completed. I just wanted to see if there is a more readable way to solve the problem. I'm basically struggling to trace the variables and I feel like there is a way to do the same thing with less variables. Any tips on utilizing the variables in recursion more effectively would be appreciated.

The program should take numerical input and output something like this

Input: 4
Output:
****
***
**
*
*
**
***
****

My code works but as I said, I feel it has some unnecessary parts in the math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
int main()
{
	
	int count;
	int lines = 0;
	
	cout << endl << "Enter an integer: ";
	cin >> count;
	
	int k = count; //to keep initial input constant
	
	drawThing(count, lines, k);
	cout << endl;
	
	return 0;
}


void drawThing(int count, int lines, int k)
{
	
	if (lines != k * 2) //Base Case
	{
		cout << endl;
		
		if (lines < k)//Recursion Case 1
                { 
		
			for (int i = 0; i < count; i++)
			{
				cout << "*";
			}
			
			
			drawThing(count - 1, lines + 1, k);
			
		}
		else // Recursion Case 2 after amount of lines is >= to the inital count
		{
			
			for (int i = 0; i < count + 1; i++) //count + 1
			{
				cout << "*";
			}
			
			drawThing(count + 1, lines + 1, k);
			
		}
		
	}

}
Last edited on
You can increment and decrement a trace variable when you enter and return from the function and print it when you like?
I have no clue why I haven't thought of that... I've been trying to do it in my head. Thanks.
I'm just trying to keep it minimal mainly and reduce unnecessary code / variables. I guess I should have made the topic clearer and asked that instead.
Last edited on
You only need one parameter: the number of stars in the line:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Draw a line of "count" stars
static void drawLine(int count)
{
    for (int i = 0; i < count; i++) {
	cout << "*";
    }
    cout << '\n';
}

void
drawThing(int count)
{
    if (count <=0 ) return;	//Base Case

    drawLine(count);
    drawThing(count - 1);
    drawLine(count);
}

Topic archived. No new replies allowed.