Inverted asterik triangle -- for(int digit = 1; digit < num-row + 1; digit++) I know it works, but why?

This is my code to create an inverted asterik triangle. It works just fine when I run the program. The problem is, I am a brand new student studying c++ and I do not want to simply copy code, I want to understand the logic behind it. Why and how does this for loop work?

for(int digit = 1; digit < num-row + 1; digit++)

I want to print one less star each time the loop iterates. I just can't wrap my head around why this works. My professor told me this would work but I actually need to understand why. Can anyone explain it in layman's terms?
Thanks!--Erin

int main()
{
int num;

cout<< "Please enter a number between 1 and 9. ";
cin>> num;
cout<< endl;

while(!cin || num < 1 || num > 9)
{
cout<< "Please enter a valid choice - a number between 1 and 9. ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin>> num;
}

for(int row = 0; row <= num; row++)
{
for(int space = 1; space <= row; space++)
{
cout<< " ";
}

for(int digit = 1; digit < num-row + 1; digit++)
{
cout<< digit;
}
cout<< endl;
}

It's just a math issue. say you enter 9 for num. Then it makes row 0, space 1 and digit 1. So that for loop becomes 1 < 9 - 0 + 1 or 1 < 10. Each iteration changes that. 2 < 9 - 1 + 1 or 2 < 9.

1 < 9 - 0 + 1 = 1 < 10
2 < 9 - 1 + 1 = 2 < 9
3 < 9 - 2 + 1 = 3 < 8
4 < 9 - 3 + 1 = 4 < 7
5 < 9 - 4 + 1 = 5 < 6

Other than that I'm not really sure what it is that you are trying to understand about the code.

Might be easier to understand if you change the code a little (just thrown together so not the best):
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

#include <iostream>
using namespace std;

int main()
{
	int num;
	cout << "Please enter a number: ";
	cin >> num;
	cout << endl;
		
	for (int row= 0; row <= num; row++)
	{
		for(int space = 1; space <= row; space++)
		{
			cout << " ";
		}
		
		for(int digit = 1; digit < num - row + 1; digit++)
		{
			cout << "*";
		}
		cout << endl;
	}
	
	return 0;
}

Tweaked it to make it simpler yet. Now it is just the for loops. In essence it is saying, for each row (first for loop) put out this number of spaces then put out this number of stars. Hope this helps figure out why that works. If not I'm sure someone else can comment and make it more clear than what I could.
Last edited on by closed account z6A9GNh0
Topic archived. No new replies allowed.