Creating an inverted triangle using **

wqdadfa
Last edited on
I've done printing of triangles with nested for loops.

Do you mean this shape?

1
2
3
4
5
6
7
8
9
10
11
for (int row=1; row<=size; row++)
	{
		for (int col=1; col<=size; col++)
		{
			if (col<=row-1)
				cout << " ";
			else
				cout << "*";
		}
		cout << endl;
	}
*******
 ******
  *****
   ****
    ***
     **
      *


or like this?

1
2
3
4
5
6
7
8
9
10
11
	for (int row=1; row<=size; row++)
	{
		for (int col=1; col<=size; col++)
		{
			if (col<=(size-row)+1)
				cout << "*";
			else
				cout << " ";
		}
		cout << endl;
	}
*******
****** 
*****  
****   
***    
**     
* 
Last edited on
closed account (28poGNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>
using namespace std;

int main ()
{
    cout << "Enter a number between 1 and 7 ->";
    int nbr;cin >> nbr;

    for(int i=nbr;i>=0;i--)
    {
        for(int j=0;j<(nbr-i);j++)
            cout << " ";
        for(int j=i*2;j>=0;j--)
        {
            cout << "*";
        }cout << endl;
    }
    
    return 0;
}
Wildblue, like the second image you posted.
is the "for" statement the same as using "while"?
I edited the post with a code snippet. Basically you can find the relationship between the numbers for the current row number, current column position and the full length of the triangle.

Row 1 - print a * position 1 through position 7 (full length(7) - row#(1) +1)
Row 2 - print a * position 1 through position 6 (full length(7) - row#(2) +1)
.
.
Row 6 - print a * position 1 through position 2 (full length(7) - row#(6) +1)
Row 7 - print a * position 1 only (full length(7) - row#(7) + 1)
Topic archived. No new replies allowed.