Loop Rules, Illegal or Legal, and Common Mistakes
LOOP RULES CHEAT SHEET
Unary Operators
Operator | Rule |
|---|---|
| Prefix: run before rest of expression |
| Postfix: run after rest of expression |
|
|
Tip | Use prefix ( |
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 |
|---|---|
| Pre-check; may run 0 times |
| Post-check; runs at least once |
| Compact; good for counters |
Loop Control
Keyword | Use |
|---|---|
| Immediately exits loop |
| 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 |
| Adds a semicolon too early: | Never end a |
Using undeclared loop variable | Declared inside loop block | Declare before loop if needed outside |
Using |
| Use |
Forgetting semicolon in | Must end with | Always check ending |
Misusing | Skips critical code updates | Put counter updates before |
Incorrect comparison |
| Always double-check |
Overusing postfix | Uses | Prefer |