- Home
- /
- Computational Thinking
- /
- Programming Fundamentals
- /
- For Loop
For Loop
Also known as: for, count-controlled loop
Grade 6-8
View on concept mapA control structure that repeats a block of code a specific number of times or once for each item in a collection. For loops are the most common loop type in programming.
Definition
A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.
π‘ Intuition
A for loop is like 'do this for each...' β for each student in the class, print their name. For each number from 1 to 10, add it to the total.
π― Core Idea
For loops are best when you know how many times to repeat or when iterating over a collection. The loop variable takes each value automatically.
Example
π Why It Matters
For loops are the most common loop type in programming. Processing lists, arrays, ranges, and any iterable collection almost always uses a for loop. They are safer than while loops because the iteration is managed automatically, reducing the risk of infinite loops.
π Hint When Stuck
When using a for loop, first identify what you are iterating overβa range of numbers or a collection of items. The loop variable is automatically assigned each value in turn. Remember that range(n) produces 0 to n-1 (not 1 to n), and check your loop bounds carefully.
Formal View
Related Concepts
π§ Common Stuck Point
range(5) gives 0 to 4, not 1 to 5. Off-by-one errors are the most common for-loop bug.
β οΈ Common Mistakes
- Off-by-one errors: range(5) gives [0,1,2,3,4], not [1,2,3,4,5]
- Modifying the collection being iterated over during the loop, causing skipped elements or errors
- Using a for loop when the number of iterations is unknownβa while loop is more appropriate in that case
Frequently Asked Questions
What is For Loop in CS Thinking?
A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.
When do you use For Loop?
When using a for loop, first identify what you are iterating overβa range of numbers or a collection of items. The loop variable is automatically assigned each value in turn. Remember that range(n) produces 0 to n-1 (not 1 to n), and check your loop bounds carefully.
What do students usually get wrong about For Loop?
range(5) gives 0 to 4, not 1 to 5. Off-by-one errors are the most common for-loop bug.
Prerequisites
Next Steps
How For Loop Connects to Other Ideas
To understand for loop, you should first be comfortable with iteration and while loop. Once you have a solid grasp of for loop, you can move on to array.