Lesson 4.4: Practice - Writing Algorithms on Paper
Duration: 45 minutes
Learning Objectives
After completing this lesson, you will be able to:
- Write complete algorithms using pseudo-code
- Create flowcharts to visualize algorithm logic
- Test your algorithms by "running" them mentally
- Debug and improve algorithms you've written
Introduction
This is a hands-on practice lesson. You've learned about algorithms, decomposition, conditions, and loops. Now it's time to put it all together and actually write algorithms.
Why paper? Professional programmers often sketch algorithms on paper or whiteboard before coding. It's faster to iterate, easier to visualize, and helps catch logical errors before you've invested time in code.
Grab a pencil and paper (or open a text editor). Let's practice!
Main Content
The Algorithm Writing Process
Before diving into exercises, here's a process to follow:
┌─────────────────────────────────────────────────────────────┐
│ ALGORITHM WRITING CHECKLIST │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. UNDERSTAND THE PROBLEM │
│ - What is the input? │
│ - What is the expected output? │
│ - What are the constraints? │
│ │
│ 2. THINK OF EXAMPLES │
│ - What happens with normal input? │
│ - What happens with edge cases? │
│ │
│ 3. WRITE THE STEPS │
│ - Start with the big picture │
│ - Add details where needed │
│ - Use conditions and loops appropriately │
│ │
│ 4. TEST YOUR ALGORITHM │
│ - Walk through with sample inputs │
│ - Check if it handles edge cases │
│ │
│ 5. REFINE │
│ - Is anything unclear? │
│ - Can anything be simplified? │
│ │
└─────────────────────────────────────────────────────────────┘
Warm-Up Exercise: Morning Coffee
Let's start simple. Write an algorithm for making coffee with a drip coffee maker.
Requirements:
- Input: Coffee grounds, water, mug
- Output: Hot cup of coffee
- Constraints: Coffee maker takes 5 minutes to brew
Take 5 minutes to write this on paper before checking the solution.
Example Solution
ALGORITHM: Make Drip Coffee
INPUT: coffee grounds, water, mug, coffee maker
OUTPUT: cup of coffee
START
1. Open coffee maker lid
2. Check if there's an old filter
3. IF old filter exists
THEN remove and discard old filter
4. Place new filter in basket
5. Add 2 tablespoons of coffee grounds to filter
6. Close filter basket
7. Open water reservoir
8. Pour 2 cups of water into reservoir
9. Close water reservoir
10. Place mug under coffee spout
11. Press power button to start
12. WHILE coffee is still brewing
Wait
13. When brewing complete, remove mug
14. Enjoy coffee
END
Exercise 1: Find the Maximum Number
Problem: Given a list of numbers, find the largest one.
Requirements:
- Input: A list of numbers (e.g., [5, 2, 9, 1, 7])
- Output: The largest number (9)
- Constraint: You can only look at one number at a time
Hints:
- You'll need a variable to store the "largest so far"
- You'll need a loop to go through each number
- You'll need a condition to compare numbers
Take 10 minutes to write this algorithm.
Example Solution
ALGORITHM: Find Maximum Number
INPUT: list of numbers
OUTPUT: the maximum number
START
IF list is empty
THEN return "Error: empty list"
END IF
SET max = first number in list
FOR EACH number IN list
IF number > max
THEN max = number
END IF
END FOR EACH
RETURN max
END
// Test with [5, 2, 9, 1, 7]:
// max starts as 5
// 2 > 5? No, max stays 5
// 9 > 5? Yes, max becomes 9
// 1 > 9? No, max stays 9
// 7 > 9? No, max stays 9
// Return 9 ✓
Exercise 2: FizzBuzz
This is a classic programming challenge. Write an algorithm that:
- Counts from 1 to 100
- For multiples of 3, say "Fizz"
- For multiples of 5, say "Buzz"
- For multiples of both 3 and 5, say "FizzBuzz"
- For other numbers, say the number
Example output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16...
Take 10 minutes to write this algorithm.
Example Solution
ALGORITHM: FizzBuzz
OUTPUT: Numbers 1-100 with Fizz/Buzz/FizzBuzz substitutions
START
FOR number FROM 1 TO 100
IF number is divisible by 3 AND divisible by 5
THEN print "FizzBuzz"
ELSE IF number is divisible by 3
THEN print "Fizz"
ELSE IF number is divisible by 5
THEN print "Buzz"
ELSE
print number
END IF
END FOR
END
// Note: "divisible by 3" means (number / 3) has no remainder
// In programming, we use: number % 3 == 0
Important: The order of conditions matters! We check for "both 3 AND 5" first because if we checked "divisible by 3" first, we'd print "Fizz" for 15 instead of "FizzBuzz".
Exercise 3: Simple Login System
Problem: Create an algorithm for a login system.
Requirements:
- User has 3 attempts to enter correct password
- Correct password is "secret123"
- After 3 failed attempts, lock the account
- Show appropriate messages
Take 10 minutes to write this algorithm.
Example Solution
ALGORITHM: Login System
INPUT: user password attempts
OUTPUT: success or account locked
START
SET correct_password = "secret123"
SET attempts = 0
SET max_attempts = 3
SET logged_in = false
WHILE attempts < max_attempts AND logged_in is false
Ask user for password
GET user_input
IF user_input equals correct_password
THEN
logged_in = true
Show "Login successful!"
ELSE
attempts = attempts + 1
SET remaining = max_attempts - attempts
IF remaining > 0
THEN Show "Incorrect password. [remaining] attempts left."
END IF
END IF
END WHILE
IF logged_in is false
THEN
Show "Account locked. Contact administrator."
Lock account
END IF
END
Exercise 4: Simple Calculator
Problem: Create an algorithm for a calculator that can add, subtract, multiply, and divide.
Requirements:
- Get two numbers from user
- Get operation (+, -, *, /)
- Handle division by zero
- Display result
- Ask if user wants to calculate again
Take 10 minutes to write this algorithm.
Example Solution
ALGORITHM: Simple Calculator
START
SET continue = true
WHILE continue is true
Show "Enter first number:"
GET number1
Show "Enter operation (+, -, *, /):"
GET operation
Show "Enter second number:"
GET number2
IF operation is "+"
result = number1 + number2
ELSE IF operation is "-"
result = number1 - number2
ELSE IF operation is "*"
result = number1 * number2
ELSE IF operation is "/"
IF number2 equals 0
THEN
Show "Error: Cannot divide by zero"
SKIP to ask for new calculation
ELSE
result = number1 / number2
END IF
ELSE
Show "Error: Unknown operation"
SKIP to ask for new calculation
END IF
Show "Result: [number1] [operation] [number2] = [result]"
Show "Calculate again? (yes/no)"
GET answer
IF answer is not "yes"
THEN continue = false
END IF
END WHILE
Show "Goodbye!"
END
Exercise 5: Guessing Game
Problem: Create a number guessing game.
Requirements:
- Computer picks a random number between 1 and 100
- User guesses the number
- Give hints: "Too high" or "Too low"
- Count the number of guesses
- Celebrate when user wins
Take 10 minutes to write this algorithm.
Example Solution
ALGORITHM: Number Guessing Game
START
SET secret_number = random number between 1 and 100
SET guesses = 0
SET won = false
Show "I'm thinking of a number between 1 and 100."
Show "Try to guess it!"
WHILE won is false
Show "Enter your guess:"
GET user_guess
guesses = guesses + 1
IF user_guess equals secret_number
THEN
won = true
Show "Congratulations! You got it!"
Show "It took you [guesses] guesses."
IF guesses <= 7
THEN Show "Excellent! That's really good!"
ELSE IF guesses <= 10
THEN Show "Good job!"
ELSE
Show "You can do better next time!"
END IF
ELSE IF user_guess < secret_number
THEN Show "Too low! Try higher."
ELSE
Show "Too high! Try lower."
END IF
END WHILE
END
Creating Flowcharts
For any algorithm you've written, try converting it to a flowchart. Here's a template:
Flowchart Symbols:
┌─────────┐
│ Rounded │ = Start/End
└─────────┘
┌─────────┐
│Rectangle│ = Process/Action
└─────────┘
╱╲
╱ ╲
╱ ╲ = Decision (Yes/No)
╲ ╱
╲ ╱
╲╱
┌─────────┐
│Parallelo│
│ gram │ = Input/Output
└─────────┘
──────→ = Flow direction
Practice: Draw a flowchart for the Login System (Exercise 3).
Flowchart Solution
┌──────────┐
│ START │
└────┬─────┘
│
▼
┌────────────────┐
│ attempts = 0 │
│ max = 3 │
└────────┬───────┘
│
┌──────────▼──────────┐
│ │
▼ │
┌───────────┐ │
╱ attempts ╲ │
╱ < max? ╲ │
╲ ╱ │
╲ ╱ │
└─────┬────┘ │
Yes │ No │
│ └────────────────┼────────┐
▼ │ │
┌───────────────┐ │ │
│ Get password │ │ │
│ from user │ │ │
└───────┬───────┘ │ │
│ │ │
▼ │ │
┌───────────┐ │ │
╱ Password ╲ │ │
╱ correct? ╲ │ │
╲ ╱ │ │
╲ ╱ │ │
└─────┬─────┘ │ │
Yes │ No │ │
┌──────┘ └──────┐ │ │
│ ▼ │ │
│ ┌────────────────┐ │ │
│ │ attempts = │ │ │
│ │ attempts + 1 │ │ │
│ └───────┬────────┘ │ │
│ │ │ │
│ └─────────────┘ │
│ │
▼ ▼
┌────────────────┐ ┌────────────────┐
│ Show "Login │ │ Show "Account │
│ successful!" │ │ locked!" │
└───────┬────────┘ └───────┬────────┘
│ │
└──────────┬─────────────────────┘
│
▼
┌─────────┐
│ END │
└─────────┘
Testing Your Algorithms
Always test your algorithms with different inputs:
| Test Type | Example | Why Test This? |
|---|---|---|
| Normal case | List: [5, 2, 9] | Basic functionality |
| Edge case | Empty list: [] | Unusual but valid input |
| Edge case | One item: [7] | Minimum valid input |
| Edge case | All same: [3, 3, 3] | Special pattern |
| Boundary | Exactly at limit | Test boundaries |
For each algorithm you wrote, ask yourself:
- What happens with an empty input?
- What happens with negative numbers?
- What happens at the boundaries?
Challenge Exercises (Optional)
If you want more practice, try these:
Challenge 1: Reverse a Word
Write an algorithm to reverse a word (e.g., "hello" becomes "olleh").
Challenge 2: Check Palindrome
Write an algorithm to check if a word is a palindrome (same forwards and backwards, like "radar" or "level").
Challenge 3: Simple Sorting
Write an algorithm to sort a list of numbers from smallest to largest.
Key Takeaways
- Writing algorithms before coding saves time and catches errors early
- Follow the process: Understand → Examples → Write → Test → Refine
- Test with different inputs: normal cases, edge cases, and boundaries
- Flowcharts help visualize the logic and find errors
- Every algorithm you write builds your problem-solving muscles
- Don't be discouraged if your first attempt isn't perfect — iteration is part of the process
What's Next?
Congratulations! You've completed Module 4: Logical Thinking. You now have the mental tools to think like a programmer:
- Understanding algorithms
- Breaking down problems
- Using conditions and loops
- Writing and testing algorithms
In the next module, you'll set up your development environment and write your first real code. The logical thinking skills you've practiced here will make that process much smoother.
Resources
| Resource | Type | Difficulty |
|---|---|---|
| Algorithm Practice - HackerRank | Practice | Beginner-Advanced |
| Flowchart Maker - Draw.io | Tool | All levels |
| Pseudocode Examples - GeeksforGeeks | Reference | Beginner |