Beginner Topic 10 of 54 Programming Fundamentals
For Loops
Counting loops with initialization, condition and increment in one header.
How it works
A for loop packages initialization, condition and update into a single header, making the iteration count explicit and keeping loop bookkeeping in one place. Range-based or for-each forms iterate directly over a collection without exposing an index. The loop variable is usually scoped to the loop, and the update step runs after each pass of the body.
Step-by-step walkthrough
- Initialization runs once: i = 0.
- The test i < 3 passes.
- The body runs for i = 0.
- The increment makes i = 1 and the test runs again.
- After i reaches 3 the test fails and the loop ends.
Where it is used
Iterating over arrays, counting from 1 to n, summing values, building tables and walking 2D grids with nested loops are classic uses. Range-based loops are the safest way to visit every item in a list or dictionary.
Common pitfall
Modifying a collection while iterating over it can skip items or throw errors. Off-by-one mistakes are common; use i < n for zero-based indexes. Changing the loop variable inside the body makes behavior hard to follow, and floating-point loop counters accumulate rounding error.
Where it fits in the course
For Loops is topic 10 of 54 in Programming Fundamentals, rated Beginner. It follows Loops. The next topic is While Loops.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is For Loops?
Where do people use For Loops?
What is the most common mistake with For Loops?
What should I learn before this topic?
How can I practice it?
Is For Loops hard to learn?
How long does it take to learn For Loops?
Which topics are related to For Loops?
What should I study after For Loops?
Related topics
- Loops (Programming Fundamentals)
- While Loops (Programming Fundamentals)
- Switch Statements (Programming Fundamentals)
- Functions (Programming Fundamentals)