Search code examples
c++visual-studio-2010for-looptext-based

I'd Like to know how to make an asterisk right triangle(S) in C++ using a loop


I want something like this:

****      ****
***        ***
**          **
*            *

I tried this:

void roadBound() {

    for( int i = 1; i <= 10; i++ ){
        for( int j = 0; j < i; j++ ){
           cout << "*" ;
        }
        cout << endl;
    }
}

But it wasnt even close. Please help


Solution

  • This uses 3 loops inside another loop

    const int ROW = 4;
    const int GAP = 7;
    
    for (int i=ROW, g=GAP; i>=0; i--, g+=2)
    {
        for (int j=0; j<i; j++) cout << '*';
        for (int j=0; j<g; j++) cout << ' ';
        for (int j=0; j<i; j++) cout << '*';
        cout << '\n';
    }
    

    Output

    ****      ****
    ***        ***
    **          **
    *            *
    

    Live code