So I managed to get the intended result for Week 1 problem set 1 Mario (less comfortable), but I'm not sure if my solution would be considered good code.

In line 11, is it ok to have subtracted by 1? Without it there would be one to many spaces (or dots) in the final result. Also in the same line, why does 's--' need a ; at the end while the 'i++' and 'j++' don't?

    for (int s = h - i - 1; s--;)

[solution code snipped]


Let's start with:

    for (int s = h - i - 1; s--;)

A FOR loop setup statement requires 3 clauses. for(init ; test ; increment ) They are separated by the semicolons. It's an absolute requirement to have the two semicolons to separate the clauses, but it is not required to have anything in any of the clauses. But, while having a blank clause is allowed, it's almost always bad form. The standard form with 3 clauses makes it clear what is controlling the loop, what the limit is, and what and how values that control the loop are being changed.

Your code combines both the test and increment clauses together. A more appropriate and more readable form would be this:

    for (int s = h - i - 1; s > 0; s--)

or even better:

    for (int s = 0; s < h - i - 1;, s++)

Yes, subtracting by 1 or decrementing is fine.

  • Ah I see, that makes a lot of sense, thanks!
    – Ryked
    May 12 '19 at 3:11
  • Hope it helped. If so, please accept the answer. Otherwise it'll sit in the unanswered question pool forever.
    – Cliff B
    May 12 '19 at 3:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .