NCO (Cyber Olympiad) /Software Applications & Programming

Loops (For, While)

Programming Fundamentals · free study notes · Updated

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:

  1. Initialization – set the loop variable(s).
  2. Condition – a Boolean expression that decides whether the loop continues.
  3. 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: or for(;;) – 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 i is automatically updated.
  • After the last iteration (i == n), the loop stops.

Explanation of the while loop

  • We manually initialize i = 1.
  • The condition i <= n is checked before each iteration.
  • Inside we add i to total and then increment i.

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.
  • for is ideal when the iteration count is known or you iterate over a sequence.
  • while is ideal when the loop continues until a runtime condition changes.
  • Always include an update step (or automatic in for) to avoid infinite loops.
  • Use break to exit early, continue to 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/Java for(init;cond;update).

Tip: When in doubt, write a small pseudocode diagram first:

init
while condition:
    body
    update

Happy looping! 🚀

Your note

Page 1

Doubt hai is topic me?

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