Loop Rules, Illegal or Legal, and Common Mistakes

LOOP RULES CHEAT SHEET


Unary Operators

Operator

Rule

++x, --x

Prefix: run before rest of expression

x++, x--

Postfix: run after rest of expression

+x, -x

+x = no effect; -x = flips sign

Tip

Use prefix (++x) for efficiency


Compound Assignment Operators

x += y;  // x = x + y;

Operator

Used For

+=

Addition

-=

Subtraction

*=

Multiplication

/=

Division

%=

Modulus (only ints)


Operator Precedence (Math Order)

Level

Operators

1

Prefix ++, --

2

Unary +, -

3

*, /, %

4

+, -

  • Use parentheses to control order: (a + b) * c


Loop Types

Type

Behavior

while

Pre-check; may run 0 times

do-while

Post-check; runs at least once

for

Compact; good for counters


Loop Control

Keyword

Use

break;

Immediately exits loop

continue;

Skips current iteration


Loop Extras

  • Sentinel = special value to stop loop (-1)

  • Infinite loop = while(true)

  • Nested loops = loop inside loop (e.g., tables)

  • Block scope = variables declared in loop stay inside loop


Tip: Always update your counter. Infinite loops happen when you don’t!


LEGAL or ILLEGAL: Loop Code Quiz

Tell whether each is Legal or Illegal:


1.

while (x < 10)
    int y = 5;
cout << y;

Illegal — y has block scope inside the loop.


2.

int i = 0;
while (i < 3) {
    cout << i;
    ++i;
}

Legal — correctly written while loop.


3.

for (int i = 10; i > 0; i++) {
    cout << i;
}

Legal — though it loops forever (i increases, never > 0 is false)


4.

do {
    cout << "Hello";
} while;

Illegal — missing () after while.


5.

for (int i = 0; i < 5; ++i)
    cout << i << endl;

Legal — one-line loop without braces.


6.

int x = 5;
int y = x++;
cout << y;

Legal — post-increment used correctly.


7.

sum =+ 5;

Illegal — typo. Should be +=, not =+.


Common Mistakes Table (Professors Love These)

Mistake

Why It Happens

How to Avoid

Infinite loop

Forgot to update counter

Always check that loop changes condition

while with ;

Adds a semicolon too early: while (x < 5);

Never end a while header with ;

Using undeclared loop variable

Declared inside loop block

Declare before loop if needed outside

Using % with doubles

% only works on integers

Use fmod() for floating point mod

Forgetting semicolon in do-while

Must end with }; while (cond);

Always check ending ;

Misusing continue

Skips critical code updates

Put counter updates before continue;

Incorrect comparison

= instead of ==

Always double-check == vs =

Overusing postfix

Uses x++ when ++x is better

Prefer ++x for better performance unless needed