### Need help with looping!

Hi everyone, my current assignment is to make two triangles out of asterisks with a width and height of a given integer (between 1 and 15).

Now, I have completed the first, as the vertex of the triangle is left justified, however on the next I need it to be right justified, and I cannot for the life of me accomplish this. I have tried several things, including tinkering with the counters, trying to include spaces, and string manipulators, but none of these things work.

 ``1234567891011121314151617181920212223242526272829`` ``````#include #include using namespace std; int main() { for (int n = x ; n >= 1; n--) { for (int k = 2; k <= n; k++) { cout << " "; } for (int j = 1; j <= n ; j++) { cout << '*'; } cout << endl; } system ("pause"); return 0; }``````

This is what I currently have. I cut out the parts of the program that aren't relevant to this portion of the problem (I have test the rest and it works), it's just that this is what's causing me issues. The for statement produces the correct number of spaces needed to complete the triangle, however it produces them in the opposite order each line (for example, if x is entered as 5, it produces 4 spaces on the first line and 0 on the 5th, which I need the opposite to happen).

Hmm, this sounds kind of similar to an exercise I had to do once... basically what you had to do was output a series of lines such that that last line contained nothing but asterisks and the first line only contained 1 asterisk. The rest was filled with periods. The asterisks had to be right justified. Here was my solution:

 ``12345678910111213141516171819202122`` ``````#include int main() { std::cout << "Enter number of rows: "; int n_Rows = 0; std::cin >> n_Rows; for (int i = 1; i <= n_Rows; i++) { for (int j = n_Rows - i; j > 0; j--) std::cout << "."; for (int k = 0; k < i; k++) std::cout << "*"; std::cout << std::endl; } return 0; }``````

and the output:

 ```Enter number of rows: 5 ....* ...** ..*** .**** *****```

The key was using a decrement operator in the first for loop to output fewer asterisks on each line, then running a regular for loop in the 2nd one. It's a definite mind-bender, took me a bit of simply sitting and thinking about exactly what each line should output and how to make the code do that for each line.
Topic archived. No new replies allowed.