Loops
Learn how to repeat code execution using for loops and while loops to automate repetitive tasks.
Use For Loops When:
- •You know exactly how many times to repeat
- •You need to count through a specific range
- •You want to process numbered items (1 to N)
- •You need the loop counter in your calculations
Use While Loops When:
- •You don't know how many iterations you need
- •The condition depends on user input or calculations
- •You're searching for something specific
- •You need more complex stopping conditions
Simple Nested Example
The inner loop runs completely for each iteration of the outer loop.
Multiplication Table
Creates a complete 5x5 multiplication table.
Accumulation Pattern
Building up a total by processing each item in sequence.
Counting Pattern
Counting items that meet specific criteria.
Search Pattern
Searching for something and stopping when found.
Validation Pattern
Limiting the number of retry attempts.
For Loop Variables
For loop variables increment automatically and don't need manual updating.
While Loop Variables
While loop variables must be updated manually to avoid infinite loops.
Infinite while loops
Forgetting to update the condition variable inside a while loop.
Always update condition variables
Use descriptive loop variable names
Instead of "i", use names like "row", "student", "attempt" for clarity.
Be careful with loop ranges
"for i from 1 to 5" includes both 1 and 5. Double-check your start and end values.