Loops in Programming
Topic: Loops (For, While)
Subject: Software Applications & Programming
Program: NCO – Cyber Olympiad
1. Simple Explanation
A loop repeatedly executes a block of code while a condition holds true.
- For‑loop: great when you know how many times you need to iterate.
- While‑loop: best when the number of iterations depends on a condition evaluated at run‑time.
Both loops consist of three parts:
- Initialization – set the loop variable(s).
- Condition – a Boolean expression that decides whether the loop continues.
- Update – change the loop variable(s) to eventually make the condition false.
2. Key Points
| Feature | for |
while |
Typical Use‑Case |
|---|---|---|---|
| Syntax | for init; condition; update { … } (C/Java/C#) |
while(condition) { … } (C/Java/C#) |
– |
| Python | for var in iterable: |
while condition: |
– |
| Loop Count Known | ✔ | ❌ | Use for |
| Loop Count Unknown | ❌ | ✔ | Use while |
| Single‑Statement Body | Implicit block (no braces in Python) | Same | – |
| Common Pitfalls | Forget update → infinite loop | Condition never true → zero iterations | – |
| Control Statements | break, continue, else (Python) |
Same | – |
Common Control Statements
break– exit the loop immediately.continue– skip the rest of the loop body and jump to the next iteration.pass– do nothing (useful for empty blocks).
Loop Types
- Single – one loop counter.
- Nested – loops inside loops (e.g., matrix traversal).
- Infinite –
while True:orfor(;;)– useful for event loops or interactive programs.
Loop Invariant
A condition that remains true before and after each iteration.
Used in proofs and debugging to ensure correctness.
3. Worked Example – “Sum of First n Natural Numbers”
We’ll solve it in Python (easy to read) but the logic works for any language.
# Problem: Compute 1 + 2 + … + n
def sum_for(n):
"""Using a for‑loop."""
total = 0
for i in range(1, n + 1): # init: i=1 ; condition: i <= n ; update: i += 1
total += i
return total
def sum_while(n):
"""Using a while‑loop."""
total = 0
i = 1 # init
while i <= n: # condition
total += i
i += 1 # update
return total
# Quick test
print(sum_for(10)) # → 55
print(sum_while(10)) # → 55
Explanation of the for loop
range(1, n+1)generates values 1 … n.- The loop variable
iis automatically updated. - After the last iteration (
i == n), the loop stops.
Explanation of the while loop
- We manually initialize
i = 1. - The condition
i <= nis checked before each iteration. - Inside we add
itototaland then incrementi.
Why use for here?
The number of iterations (n) is known in advance, so a for loop is concise and eliminates manual update errors.
4. Quick Revision Summary
- Loops repeat code while a condition is true.
foris ideal when the iteration count is known or you iterate over a sequence.whileis ideal when the loop continues until a runtime condition changes.- Always include an update step (or automatic in
for) to avoid infinite loops. - Use
breakto exit early,continueto skip the rest of the current iteration. - Remember that loop invariants help prove correctness.
- For nested loops, total complexity is often the product of the inner and outer loop bounds.
- In Python,
for variable in iterable:replaces the classic C/Javafor(init;cond;update).
Tip: When in doubt, write a small pseudocode diagram first:
init while condition: body update
Happy looping! 🚀