Forrest Walker Forrest Walker - 2 months ago 17
C++ Question

Creating a parallelogram with for loops

Hello I am trying to create a parallelogram and am having a bit a trouble so far I have

void stars(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
cout << " ";
}
else cout << "*";
}
cout << endl;
}
}


So stars(7) prints

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


however i need it to print like this

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


my function is moving the spaces over correctly but it is decreasing the amount of stars as well, how can i continue to move the stars over but without losing the number of stars?

Answer

Do not make printing stars conditional. Print i spaces then n stars.

for(int i = 0; i < n; ++i) {
    for(int j = 0; j < i; ++j) {
        cout << ' ';
    }
    for(int j = 0; j < n; ++j) {
        cout << '*';
    }
    cout << '\n';
}

live example

That being said, this isn't very readable, I'd rather go with: (or Lassie's answer)

string nstars(n, '*');
for(int i = 0; i < n; ++i) {
    cout << string(i, ' ') << nstars << '\n';
}

live example

This creates a std::strings of i spaces and n stars. It carries the cost of additional allocations, but readability is often more important, especially for small toy projects.

And if you're more into stdlib algorithms:

for(int i = 0; i < n; ++i) {
    fill_n(ostream_iterator<char>(cout), i, ' ');
    fill_n(ostream_iterator<char>(cout), n, '*');
    cout << '\n';
}

I don't think this should be any worse than the first loop, but it may look scary for newbies.