0

I want to create a condition so that blank will not turn negative due to the blank -=1. For example if n = 3, blank = 1 therefore will print two "#", however I want it to stop at 0 when it loops

Here's my code

for (int blank = n-2; blank < n; blank -=1) 
    printf("#");
printf("\n");

something like this is what i'm trying to achieve

for (int blank = n-2; blank < n or blank > 0; blank -=1) 
    printf("#");
printf("\n");

or

for (int blank = n-2; blank < n; blank -=1) 
printf("#");
    {
        if (blank == 0) break;
    }
    printf("\n");

thank you

Eric Chee
  • 7
  • 3
  • Does this answer your question? [Multiple conditions in a C 'for' loop](https://stackoverflow.com/questions/16859029/multiple-conditions-in-a-c-for-loop) – Aiden Yeomin Nam Jan 12 '20 at 23:43

2 Answers2

0

Just use a logical OR

blank < n or blank > 0 can be represented as:

(blank < n) || (blank > 0)

jmq
  • 1,559
  • 9
  • 21
0

You used "or" in your pseudocode, but you really want to loop while blank is less n and while blank is greater than 0. && is the logical-and operator, so you could use the following:

for (int blank = n-2; blank < n && blank > 0; blank -= 1) 

But blank < n is always true, so you can simply use the following:

for (int blank = n-2; blank > 0; blank -= 1) 

Note that i -= 1 can be written --i for integer types.

for (int blank = n-2; blank > 0; --blank)     # blank goes from n-2 to 1

This would produce the same outcome:

for (int blank = n-2; blank-- > 0; )          # blank goes from n-3 to 0

If n was guaranteed to be at least 2, you could also use a common idiom:

for (int blank = n-2; blank--; )              # blank goes from n-3 to 0 if n>=2
ikegami
  • 367,544
  • 15
  • 269
  • 518