NCO (Cyber Olympiad) /Software Applications & Programming

Loops (For, While)

Programming Fundamentals · free study notes

Loops (For, While) – Quick Study Notes

(for the NCO Cyber Olympiad – Software Applications & Programming)


1. What Is a Loop?

  • A loop tells the computer to do the same thing again and again.
  • Think of it like a chore list: “Wash dishes, then wash dishes, then wash dishes…” until you have finished.

2. Why Use Loops?

  • Saves time: you don’t write the same line over and over.
  • Makes your program flexible: the number of repeats can change based on input.

3. Two Main Types of Loops

Type When to Use Simple Analogy
For Loop When you know exactly how many times you want to repeat. “Walk 10 steps.”
While Loop When you want to repeat until something happens. “Keep rinsing until the water is clear.”

4. The For Loop

How It Looks

for i in range(5):   # 5 times
    print(i)

What Happens

  1. i starts at 0.
  2. The code inside the loop runs.
  3. i moves to 1, 2, 3, 4.
  4. After 5, the loop stops.

Everyday Analogy

  • Counting to 5:
    • “Say 1, say 2, say 3, say 4, say 5.”
    • Then stop.

Tiny Example – Print Numbers 1‑5

for num in range(1, 6):
    print(num)

5. The While Loop

How It Looks

count = 0
while count < 5:
    print(count)
    count += 1

What Happens

  1. Check the condition (count < 5).
  2. If true, run the code inside.
  3. Update count.
  4. Go back to step 1.
  5. Stop when the condition is false.

Everyday Analogy

  • Rinse until clean:
    • “If the dish is still dirty, rinse it, then check again.”
    • Stop when it’s clean.

Tiny Example – Print Numbers 0‑4

x = 0
while x < 5:
    print(x)
    x += 1

6. Choosing Between For and While

Situation Prefer For Prefer While
You know how many times (e.g., 10 loops) ✅ ❌
You need to keep going until a condition changes (e.g., input > 0) ❌ ✅

7. Things to Remember

  1. Always change something inside the loop (like i += 1 or count += 1).
    • If you don’t, the loop will never end – an infinite loop.
  2. Keep the loop body small and clear.
  3. Think of loops like a “do‑something‑again” command.

8. Common Mistakes

Mistake Fix
Forgetting to update the counter Add i += 1 or count += 1 inside the loop.
Wrong condition Double‑check the comparison (<, <=, >, >=).
Mixing up for and while Use for when you know the exact count, while when you don’t.

9. Quick Practice

  1. For Loop – Print the letters of the word “HELLO”.
  2. While Loop – Keep asking the user for a number until they type 0.

(Try writing these on your own before looking at the solutions.)


10. Summary

  • Loops repeat actions.
  • For – repeat a fixed number of times.
  • While – repeat until something is no longer true.
  • Always update the loop variable; otherwise, you’ll trap the computer in a never‑ending cycle.

Happy looping! 🚀

Your note

Page 1

Doubt hai is topic me?

Free AI teacher se poocho — 24/7, step by step.