Q:

Nested For Loop Triangle in C++

I'm trying to write a nested for loop that prints out this pattern:
x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxx
xxxxx
xxx
x

However, I don't know how to make the coloumn have two more stars than the last one.
This is the code I have so far:
#include <iostream>
using namespace std;

int main()
{
    for(int r = 1; r <= 5; r++)
    {
        for(int c = 1; c <= r; c++)
            cout << "*";
            cout<< endl;
    }
    for(int r1 = 5; r1 >= 1; r1--)
    {
        for(int c1 = 1; c1 <= r1; c1++)
            cout << "*";
            cout<< endl;
    }
    return 0;
}

I'd appreciate it if someone can help me figure this out.

A:

What you have now is close, the inner loop termination condition is wrong.
Observe that you need to print 1,3,5,7,9 *s while the row index are 1,2,3,4,5. So the number of * to print is: 2*rowIndex -1.
for(int r = 1; r <= 5; r++){
    for(int c = 1; c <= 2*r -1; c++)
                   //^^^Here is the diff
             cout << "*";
        cout<< endl;
}
for(int r1 = 5; r1 >= 1; r1--){
        for(int c1 = 1; c1 <= 2*r1 -1; c1++)
                        //^^same here
                cout << "*";
        cout<< endl;
}
return 0;

You can see a live demo here:Print Triangle Star pattern

