Nested For Loop: Vertical (*) Triangles

I can't figure this out. I have to place two asterisk triangles on top of each other BUT only using 3 for statements. I have gotten the first one:

for(int a=1;a<=10;a++)
{

for(int b=1;b<=a;b++)
cout << "*";
cout << endl;
}
I need the output to look like this:
*
**
***
****
*****
******
*******
********
*********
**********
*
**
***
****
*****
******
*******
********
*********
**********

The only kicker is I can have a total of 3 nested for loop statements.
Help please!! :)
The % operator may help.

-Albatross
I don't see the issue...

Why don't you just try and solve it first. This really isn't a difficult problem.
Last edited on
1
2
3
4
5
6
for(int a=1;a<=10;a++)
{
    for(int b=1;b<=a;b++)
        cout << "*";
    cout << endl;
}


If this gives you a triangle, it should be really easy to get a second one with just another for loop. all you need to do is repeat this code again.
so ...

1
2
for(int i=0; i<2; ++i)
   your triangle code

I am so new at programming period. This is my first ever class of it. I can't seem to get the triangles on top of each other because I can only use 3 FOR loops. I can get it to work with no problems using 4 FOR loops but not 3. I keep getting this solution:

*
*
**
**
***
***
****
****
*****
*****
******
******
*******
*******
********
********
*********
*********
**********
**********
> I can only use 3 FOR loops.

You need only two.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
    int n = 10 ;

    for( int i = 0 ; i < n*2 ; ++i ) // i in [ 0 1 2 ... 8 9 10 11 12 ... 18 19 ]
    {
        int nstars = i%n + 1 ;  // nstars in [ 1 2 3 ... 9 10 1  2  3...   9 10 ]
        for( int j = 0 ; j < nstars ; ++j ) std::cout << '*' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/391552eb7be49075
Thank you kind sir/maam. That was easier than I was trying to make it out to be.
That was what Albatross had suggested.

This is what Darkmaster had suggested (three loops):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    int n = 10 ;
    int ntriangles = 2 ;
    
    for( int i = 0 ; i < ntriangles ; ++i )
    {
        for( int a = 1 ; a <= n ; ++a )
        {
            for( int b = 1 ; b <= a ; ++b ) std::cout << '*' ;
            std::cout << '\n' ;
        }
    }
}

http://coliru.stacked-crooked.com/a/83ec57704c4ebe1b
Topic archived. No new replies allowed.