Lesson 8 • Intermediate

Loops

30 minutes
Control Flow

🔁 What are Loops?

Loops allow you to repeat code multiple times without writing it over and over. They're essential for processing lists, repeating actions, and iterating through data.

Why Loops Matter
Imagine you need to print numbers 1 to 100. Without loops, you'd write 100 Print statements! With a loop, it's just a few lines of code. Loops make your programs efficient and scalable.

Visual: How Loops Work

1️⃣
i = 1
2️⃣
i = 2
3️⃣
i = 3
4️⃣
i = 4
5️⃣
i = 5
Loop repeats code for each value
For i = 1 To 5 → Executes 5 times

🔢 FOR Loop

Use FOR loops when you know how many times to repeat:

For variable = start To end
    # Code to repeat
Endfor
Example: Simple FOR Loop
Algorithm CountToTen

Print "Counting from 1 to 10:"

For i = 1 To 10
    Print i
Endfor

Print "Done!"

Endalgorithm
Output
Counting from 1 to 10: 1 2 3 4 5 6 7 8 9 10 Done!

FOR Loop with Step

Use Step to change the increment:

Example: FOR Loop with Step
Algorithm CountByTwos

# Count by 2s
Print "Even numbers from 0 to 10:"
For i = 0 To 10 Step 2
    Print i
Endfor

Print ""

# Countdown
Print "Countdown:"
For i = 10 To 1 Step -1
    Print i
Endfor
Print "Blast off! 🚀"

Endalgorithm
Output
Even numbers from 0 to 10: 0 2 4 6 8 10 Countdown: 10 9 8 7 6 5 4 3 2 1 Blast off! 🚀

🌀 WHILE Loop

WHILE loops repeat as long as a condition is true:

While condition Do
    # Code to repeat
    # IMPORTANT: Update condition to avoid infinite loop!
Endwhile
Example: WHILE Loop
Algorithm WhileExample

var count = 1

Print "Counting with WHILE:"

While count <= 5 Do
    Print "Count:", count
    count = count + 1  # MUST update counter!
Endwhile

Print "Done! Final count:", count

Endalgorithm
Warning: Infinite Loops!

Always update the loop variable in WHILE loops, or they'll run forever!

❌ Bad (infinite loop):

var x = 1
While x <= 5 Do
    Print x
    # Forgot to update x! Will loop forever!
Endwhile

✅ Good (will end):

var x = 1
While x <= 5 Do
    Print x
    x = x + 1  # Updates x so loop will end
Endwhile

🔁 REPEAT-UNTIL Loop

REPEAT-UNTIL executes at least once, then repeats until a condition becomes true:

Repeat
    # Code to repeat (runs at least once)
Until condition
Example: REPEAT-UNTIL Loop
Algorithm RepeatUntilExample

var password = ""
var correctPassword = "secret123"

Print "=== Login System ==="

Repeat
    password = Input "Enter password:"
    
    If password != correctPassword Then
        Print "❌ Incorrect! Try again."
        Print ""
    Endif
    
Until password == correctPassword

Print "✅ Access granted!"

Endalgorithm

Choosing the Right Loop

Loop Type When to Use Example Use Case
FOR Know the number of iterations Count 1 to 10, process array elements
WHILE Don't know iteration count, check condition first Read until end of file, user input validation
REPEAT-UNTIL Must execute at least once Menu systems, input validation

📊 Common Loop Patterns

1. Accumulator Pattern

Sum up values:

Example: Calculate Sum
Algorithm CalculateSum

var total = 0

Print "Calculating sum of 1 to 100..."

For i = 1 To 100
    total = total + i
Endfor

Print "Sum:", total

Endalgorithm

2. Counter Pattern

Count occurrences:

Example: Count Evens and Odds
Algorithm CountEvenOdd

var evenCount = 0
var oddCount = 0

For i = 1 To 20
    If i mod 2 == 0 Then
        evenCount = evenCount + 1
    Else
        oddCount = oddCount + 1
    Endif
Endfor

Print "Even numbers:", evenCount
Print "Odd numbers:", oddCount

Endalgorithm

3. Find Maximum/Minimum

Example: Find Maximum
Algorithm FindMaximum

var max = 0
var count = 5

Print "Enter", count, "numbers:"

For i = 1 To count
    var number = Input "Number" + i + ":"
    
    If i == 1 Then
        max = number  # First number is max initially
    Else
        If number > max Then
            max = number
        Endif
    Endif
Endfor

Print ""
Print "Maximum value:", max

Endalgorithm

🎮 Real-World Examples

Example: Multiplication Table
Algorithm MultiplicationTable

var number = Input "Enter a number:"

Print ""
Print "=== Multiplication Table for", number, "==="
Print ""

For i = 1 To 10
    var result = number * i
    Print number, "×", i, "=", result
Endfor

Endalgorithm
Example: Factorial Calculator
Algorithm FactorialCalculator

var n = Input "Enter a number:"
var factorial = 1

Print ""
Print "Calculating", n, "! ..."

For i = 1 To n
    factorial = factorial * i
    Print i, "! =", factorial
Endfor

Print ""
Print "Final result:", n, "! =", factorial

Endalgorithm
Example: Menu System
Algorithm MenuSystem

var choice = 0

Repeat
    Print ""
    Print "=== MAIN MENU ==="
    Print "1. Say Hello"
    Print "2. Show Date"
    Print "3. Calculator"
    Print "4. Exit"
    Print ""
    
    choice = Input "Enter choice (1-4):"
    
    If choice == 1 Then
        Print "👋 Hello, World!"
    Else If choice == 2 Then
        Print "📅 Today is October 5, 2025"
    Else If choice == 3 Then
        var a = Input "Enter first number:"
        var b = Input "Enter second number:"
        Print "Sum:", a + b
    Else If choice == 4 Then
        Print "👋 Goodbye!"
    Else
        Print "❌ Invalid choice! Try again."
    Endif
    
Until choice == 4

Endalgorithm
Example: Guessing Game
Algorithm GuessingGame

var secretNumber = 42
var maxTries = 5
var tries = 0
var won = false

Print "=== NUMBER GUESSING GAME ==="
Print "I'm thinking of a number between 1 and 100"
Print "You have", maxTries, "tries!"

While tries < maxTries and won == false Do
    tries = tries + 1
    
    Print ""
    var guess = Input "Guess #" + tries + ":"
    
    If guess == secretNumber Then
        won = true
        Print "🎉 Correct! You won in", tries, "tries!"
    Else
        If guess < secretNumber Then
            Print "📈 Too low!"
        Else
            Print "📉 Too high!"
        Endif
        
        var remaining = maxTries - tries
        If remaining > 0 Then
            Print "Tries remaining:", remaining
        Endif
    Endif
Endwhile

If won == false Then
    Print ""
    Print "💔 Game Over! The number was", secretNumber
Endif

Endalgorithm

Key Takeaways

  • ✅ FOR loops: Use when you know iteration count
  • ✅ WHILE loops: Use when condition-based, check before executing
  • ✅ REPEAT-UNTIL: Use when must execute at least once
  • ✅ Always update loop variables to avoid infinite loops
  • ✅ Use Step to change increment in FOR loops
  • ✅ Common patterns: accumulator, counter, find max/min
  • ✅ Close loops with Endfor, Endwhile, or Until

💪 Practice Exercises

Try These Exercises

Exercise 1: Fibonacci Sequence
Generate the first N numbers of the Fibonacci sequence (each number is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8...).
Exercise 2: Prime Number Checker
Check if a number is prime by testing if it's divisible by any number from 2 to n-1 using a loop.
Exercise 3: Average Calculator
Ask user how many numbers they want to average, then use a loop to get those numbers and calculate the average.
Exercise 4: Pattern Printer
Create a program that prints a star triangle pattern (1 star on first line, 2 on second, 3 on third, etc.) up to N lines.
Excellent Work!
You now understand how to repeat actions using loops! In the next lesson, we'll explore nested loops to create more complex patterns and work with 2D data.