












Loops in Programming
For, While, Nested Loops
What are Loops in Programming?
Loops are used to execute a block of code repeatedly as long as a given condition is true. They help reduce code duplication and are essential in tasks like traversing arrays, repeating calculations, or processing input.
Why Use Loops?
- To repeat a task multiple times efficiently
- To iterate over collections like arrays or lists
- To automate repetitive logic
Types of Loops
- For Loop – Runs a block of code for a defined number of times
- While Loop – Continues until a condition becomes false
- Do While Loop – Similar to while loop, but runs at least once
For Loop Example
Let’s print numbers from 1 to 5 using a for loop.
for i = 1 to 5:
print(i)
1 2 3 4 5
How it works:
The loop starts at 1 and increments i
by 1 until it reaches 5. Each time, the value of i
is printed.
Question:
What happens if we change the condition to go from 5 to 1?
Answer:
You need to decrement i
instead of incrementing:
for i = 5 to 1 step -1:
print(i)
5 4 3 2 1
While Loop Example
This loop continues while a condition is true.
i = 1
while i <= 5:
print(i)
i = i + 1
1 2 3 4 5
Explanation:
The loop starts with i = 1
. Each iteration increases i
by 1. When i
becomes 6, the condition i <= 5
is false, and the loop exits.
Question:
What if we forget to increment i
?
Answer:
The loop will never end, resulting in an infinite loop. Always ensure there's a termination condition being met.
Do While Loop Example
This loop executes at least once, even if the condition is false.
i = 10
do:
print(i)
i = i + 1
while i <= 5
10
Explanation:
Even though the condition is false at the start, the loop body runs once before checking it.
Nested Loops
Loops inside loops are called nested loops. These are useful for working with 2D data like grids or matrices.
for i = 1 to 3:
for j = 1 to 2:
print("i =", i, ", j =", j)
i = 1 , j = 1 i = 1 , j = 2 i = 2 , j = 1 i = 2 , j = 2 i = 3 , j = 1 i = 3 , j = 2
Common Loop Pitfalls
- Forgetting to update the loop variable → leads to infinite loops
- Off-by-one errors → start or stop values miscalculated
- Breaking out of a loop too early or too late
Summary
- Use
for
loops when the number of iterations is known - Use
while
loops when the condition is evaluated dynamically - Use
do while
loops to ensure the code block runs at least once
Quick Intuition Check
Q: How many times will the following loop run?
i = 1
while i < 4:
print(i)
i = i + 1
A: It will print 1, 2, and 3 — 3 times in total.