Nested Loops in C++

Hi! I have been working on creating different types of right triangles with nested loops. So far, I have succeeded with most of them except for the mirrored one. (1 asterick on top and 7 on the bottom, aligned to the right)

This is the code I have so far:

#include <iostream>
using namespace std;

int main(){
char character;
int n;

cout << "Enter a character: ";
cin >> character;
cout << "Enter number of rows: ";
cin >> n;
cout << endl;

for (int i = 1; i <= n; ++i){
for (int s = n-i; s >= 1; --s)
cout << " ";
for (int j = 1; j <= i; ++j){
cout << character << " ";
}
cout << endl;
}

return 0;
}

However, every time I run it, the output looks like a regular triangle, not a right triangle.

How do I fix this? Thank you!
Last edited on
Looks like you need double the number of leading spaces.
Try changing line 16 from
 
    cout << " ";
to
 
    cout << "  ";


By the way, it helps to make posts more readable if you use code tags,
[output]program output[/output]
and
[code]program code[/code]

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


      * 
     * * 
    * * * 
   * * * * 
  * * * * * 
 * * * * * * 
* * * * * * * 
You do print n columns on each row, don't you? Some columns are empty, some not.

This is how you apparently print an empty column:
cout << " ";
one whitespace character

This is how you print a non-empty column:
cout << character << " ";
one whitespace and one asterisk == two characters


Apparently, for the lack of code tags in posted code creates uncertainty.
See http://www.cplusplus.com/articles/jEywvCM9/
You can edit your post.
Looks like you need double the number of leading spaces.
Try changing line 16 from

cout << " ";
to

cout << " ";


By the way, it helps to make posts more readable if you use code tags,
program output

and
program code

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


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


this worked! thank you so much!
also thanks for the tip! I'm new to this site so I'm still learning
Topic archived. No new replies allowed.