2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by deceptikon
0

This is actually an amusing exercise, but if you can really only use one loop then you'll need to employ a trick of two that technically involves an implicit loop. Since you're essentially working with a 2D grid (ie. rows and columns) at least two loops are necessary to get the job done.

For example, in this solution the implicit loop is established using setw() and setfill():

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
    int n = 5;

    for (int i = 1; i <= n; ++i) {
        cout << setw(n - i) << setfill(' ') << "" 
             << setw(i) << setfill('*') << "" 
             << endl;
    }
}

Of course, that doesn't work for you (intentionally) because it doesn't include an if statement, but it's an interesting exhibition of ostream manipulators.

The first thing I'd suggest is to verify that you can't use nested loops, because a single explicit loop is somewhat tricky and I'd call it a more advanced exercise because of that restriction.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.