Selection And Iteration Code Guides: FOR Loops: Structure, Use Cases And Pitfalls (Copy)
FOR Loops: Structure, Use Cases And Pitfalls
What A FOR Loop Is (Count-Controlled Iteration)
- A FOR loop repeats a block of code a known number of times
- You use it when:
- The number of repetitions is fixed (e.g., 10 times)
- You must process a fixed range of values (e.g., 1 to n)
- You want to traverse an array/list by index safely
- Core idea
- A counter variable automatically changes each iteration until the loop finishes
Standard FOR Loop Structure (Pseudocode)
- Basic form
FOR counter ← start TO end<statements>NEXT counter
- With step
FOR counter ← start TO end STEP stepValue<statements>NEXT counter
- Key exam-safe assumptions
startandendare treated as inclusive- If no
STEPis given, default is usuallySTEP 1
Counter, Start, End, Step (Roles + Mistake Traps)
| Component | Purpose | Correct Use | Pitfall That Loses Marks |
|---|---|---|---|
| Counter | Tracks iteration number | i, index, attempt |
Changing counter inside loop |
| Start | First value for counter | 1 or 0 depending on indexing |
Starting at wrong bound |
| End | Last value to reach | n, 10, LEN(arr) type logic |
Off-by-one (missing last item) |
| STEP | Increment/decrement size | 2, -1, etc. |
Wrong sign when counting down |
When A FOR Loop Is The Best Choice (Vs Other Loops)
| Task | Best Loop | Why |
|---|---|---|
| Repeat exactly 20 times | FOR | Count known |
| Traverse array indices | FOR | Controlled index range |
| Keep asking until valid input | WHILE / REPEAT UNTIL | Repetitions unknown |
| Stop as soon as condition met | WHILE (or FOR with flag) | FOR needs safe early-exit logic |
Written and Compiled By Sir Hunain Zia (AYLOTI), World Record Holder With 154 Total A Grades, 7 Distinctions and 11 World Records For Educate A Change AS Level Computer Science Full Scale Course
Structure (How To Write It Correctly Every Time)
Template 1: Simple Count Loop
- Use when you need a fixed number of repetitions
FOR i ← 1 TO 10
OUTPUT i
NEXT i
- What it does
- Outputs: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Template 2: Range With A Step
- Use to skip values or count backwards
FOR i ← 2 TO 20 STEP 2
OUTPUT i
NEXT i
- What it does
- Outputs: 2, 4, 6, 8, … , 20
Template 3: Counting Down
FOR i ← 10 TO 1 STEP -1
OUTPUT i
NEXT i
- What it does
- Outputs: 10, 9, 8, … , 1
Use Cases (Code + Application-Based Examples)
Use Case 1: Repeat A Task Exactly N Times
- Scenario
- A system needs to display a message exactly 5 times
FOR i ← 1 TO 5
OUTPUT "Welcome"
NEXT i
- Marks usually come from
- Correct bounds
- Correct output statement inside loop
Use Case 2: Summation (Adding Many Values)
- Scenario
- Input 10 numbers, output their sum
total ← 0
FOR i ← 1 TO 10
INPUT num
total ← total + num
NEXT i
OUTPUT total
- Common examiner marking points
total ← 0before the loop- update uses
total ← total + numnot overwriting
- Pitfall
- Writing
total ← num(kills the sum)
- Writing
Use Case 3: Counting Matches (Selection Inside Iteration)
- Scenario
- Input 8 numbers, count how many are even
countEven ← 0
FOR i ← 1 TO 8
INPUT num
IF num MOD 2 = 0 THEN
countEven ← countEven + 1
ENDIF
NEXT i
OUTPUT countEven
- Why this matters
- Shows controlled repetition + IF logic (common paper pattern)
- Pitfalls
- Using
/instead ofMOD - Forgetting
ENDIF
- Using
Use Case 4: Processing A 1D Array By Index
- Scenario
- Marks stored in
marks[1..5], find total
- Marks stored in
total ← 0
FOR index ← 1 TO 5
INPUT marks[index]
total ← total + marks[index]
NEXT index
OUTPUT total
- Pitfall (array out of range)
- Accidentally looping
1 TO 6
- Accidentally looping
Written and Compiled By Sir Hunain Zia (AYLOTI), World Record Holder With 154 Total A Grades, 7 Distinctions and 11 World Records For Educate A Change AS Level Computer Science Full Scale Course
Use Case 5: Find Maximum (Safe Exam Pattern)
- Scenario
- Find largest number in an array
arr[1..n]
- Find largest number in an array
- Safe method
- Set max to first element (works even if all values are negative)
INPUT n
FOR i ← 1 TO n
INPUT arr[i]
NEXT i
max ← arr[1]
FOR i ← 2 TO n
IF arr[i] > max THEN
max ← arr[i]
ENDIF
NEXT i
OUTPUT max
- Pitfall
max ← 0(fails if values are all negative)
Use Case 6: Average Of Values
- Scenario
- Input n values, output average
INPUT n
total ← 0
FOR i ← 1 TO n
INPUT num
total ← total + num
NEXT i
average ← total / n
OUTPUT average
- Pitfalls
- Forgetting to divide by
n - Dividing inside loop (logic still possible but messy and risky)
- Forgetting to divide by
Use Case 7: Building A Frequency Count
- Scenario
- Count how many numbers are greater than 50
countHigh ← 0
FOR i ← 1 TO n
INPUT num
IF num > 50 THEN
countHigh ← countHigh + 1
ENDIF
NEXT i
OUTPUT countHigh
- Why examiners like it
- Clear count-controlled loop + clear condition
Nested FOR Loops (When + How)
What Nested FOR Loops Are Used For
- Traversing a 2D array
- Creating a grid output (tables, matrices)
- Checking every combination (not always efficient, but common in exam tasks)
Example: 2D Array Input And Output
- Scenario
- Read a 3×4 grid and output it
FOR row ← 1 TO 3
FOR col ← 1 TO 4
INPUT grid[row][col]
NEXT col
NEXT row
FOR row ← 1 TO 3
FOR col ← 1 TO 4
OUTPUT grid[row][col]
NEXT col
NEXT row
Nested Loop Pitfalls
- Reusing the same counter name
- Wrong:
FOR i ← 1 TO 3FOR i ← 1 TO 4
- Wrong:
- Incorrect
NEXTplacement (closing wrong loop) - Misunderstanding total iterations
- Total = rows × cols
Written and Compiled By Sir Hunain Zia (AYLOTI), World Record Holder With 154 Total A Grades, 7 Distinctions and 11 World Records For Educate A Change AS Level Computer Science Full Scale Course
Tracing A FOR Loop (Dry Run Method That Always Works)
Tracing Checklist
- Create a table with:
- counter value
- important variable(s) (total/count/max)
- output if any
- Execute loop body line-by-line
- After body ends, counter updates automatically
Worked Trace Example
total ← 0
FOR i ← 1 TO 4
total ← total + i
NEXT i
OUTPUT total
| i | total before | total after |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 3 | 6 |
| 4 | 6 | 10 |
- Output:
10
Pitfalls (The Ones That Constantly Destroy Marks)
Pitfall 1: Off-By-One Errors
- Example mistake
- Array
arr[1..n]but loop does:FOR i ← 1 TO n - 1
- Misses last element
- Array
- Fix
- Write the array bounds first, then match the loop
Pitfall 2: Array Index Out Of Range
- Example mistake
FOR i ← 1 TO n- Accessing
arr[i + 1] - When
i = n,arr[n + 1]is invalid
- Fix options
- Loop only to
n - 1 - Or change logic to avoid
i + 1
- Loop only to
Pitfall 3: Wrong STEP Sign When Counting Down
- Wrong
FOR i ← 10 TO 1 STEP 1
- Correct
FOR i ← 10 TO 1 STEP -1
Pitfall 4: Changing Counter Inside Loop
- Wrong
FOR i ← 1 TO 10
i ← i + 1
OUTPUT i
NEXT i
- Why wrong
- Skips values unpredictably
- Correct approach
- Use
STEP:
- Use
FOR i ← 1 TO 10 STEP 2
OUTPUT i
NEXT i
Written and Compiled By Sir Hunain Zia (AYLOTI), World Record Holder With 154 Total A Grades, 7 Distinctions and 11 World Records For Educate A Change AS Level Computer Science Full Scale Course
Pitfall 5: Not Initialising Variables
- Common fails
- Using
totalwithout settingtotal ← 0 - Using
countwithout settingcount ← 0
- Using
- Fix
- Always initialise before loop begins
Pitfall 6: Using FOR When Repetitions Are Unknown
- Bad scenario
- Input validation:
- “Keep asking until correct”
- Input validation:
- Better pattern
- Pre-condition or post-condition loop instead (FOR is not natural here)
“Copy-Paste Patterns” Students Should Memorise
Pattern A: Total Of N Inputs
INPUT n
total ← 0
FOR i ← 1 TO n
INPUT num
total ← total + num
NEXT i
OUTPUT total
Pattern B: Count Items That Match A Condition
count ← 0
FOR i ← 1 TO n
IF <condition> THEN
count ← count + 1
ENDIF
NEXT i
OUTPUT count
Pattern C: Maximum Value In Array
max ← arr[1]
FOR i ← 2 TO n
IF arr[i] > max THEN
max ← arr[i]
ENDIF
NEXT i
OUTPUT max
Pattern D: Reverse Traversal
FOR i ← n TO 1 STEP -1
OUTPUT arr[i]
NEXT i
Quick “Spot The Mistake” Mini Practice (Exam-Style)
Q1 (Bug In Summation)
total ← 0
FOR i ← 1 TO 5
INPUT num
total ← num
NEXT i
OUTPUT total
- What’s wrong
- Overwrites total instead of adding
- Fix
total ← total + num
Q2 (Bug In Reverse Loop)
FOR i ← 5 TO 1
OUTPUT i
NEXT i
- What’s wrong
- Missing
STEP -1
- Missing
- Fix
FOR i ← 5 TO 1 STEP -1
Q3 (Bug In Array Bounds)
- Array is
arr[1..10], loop:FOR i ← 0 TO 9
- What’s wrong
- Wrong range for this indexing system
- Fix
FOR i ← 1 TO 10
