Lesson 20Control Flow
Control Flow Practice
Module Review
Congratulations! You've learned all the control flow concepts. Let's practice combining them to solve real problems!
What You've Learned
ifelseswitchfor-inwhilerepeatbreakcontinueguardrangesPractice Challenges
1. FizzBuzz
Print 1-20: "Fizz" for multiples of 3, "Buzz" for 5, "FizzBuzz" for both
2. Grade Calculator
Convert numeric scores to letter grades using switch
3. Prime Finder
Find all prime numbers between 1 and 50
4. Guessing Game
Guess a secret number with "too high/low" hints
5. Input Validation
Use guard to validate user registration
6. Pattern Printing
Create triangle patterns with nested loops
Module Complete!
You've mastered Control Flow in Swift! You can now make your programs smart and responsive. Next up: Collections!
main.swift
// ===== CONTROL FLOW PRACTICE =====
// Challenge 1: FizzBuzz
print("--- FizzBuzz ---")
for i in 1...20 {
if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
} else if i % 3 == 0 {
print("Fizz")
} else if i % 5 == 0 {
print("Buzz")
} else {
print(i)
}
}
// Challenge 2: Grade Calculator
print("\n--- Grade Calculator ---")
let scores = [95, 82, 76, 68, 55, 91]
for score in scores {
let grade: String
switch score {
case 90...100: grade = "A"
case 80..<90: grade = "B"
case 70..<80: grade = "C"
case 60..<70: grade = "D"
default: grade = "F"
}
print("Score \(score) = Grade \(grade)")
}
// Challenge 3: Find Prime Numbers
print("\n--- Prime Numbers (1-50) ---")
var primes: [Int] = []
for num in 2...50 {
var isPrime = true
for divisor in 2..<num {
if num % divisor == 0 {
isPrime = false
break
}
}
if isPrime {
primes.append(num)
}
}
print(primes)
// Challenge 4: Number Guessing Game
print("\n--- Guessing Game ---")
let secret = 7
var guess = 0
var attempts = 0
while guess != secret {
attempts += 1
guess = Int.random(in: 1...10)
if guess < secret {
print("\(guess) - Too low!")
} else if guess > secret {
print("\(guess) - Too high!")
} else {
print("\(guess) - Correct in \(attempts) tries!")
}
}
// Challenge 5: Validate User Input
print("\n--- Input Validation ---")
func validateUser(name: String?, email: String?, age: Int?) -> Bool {
guard let userName = name, !userName.isEmpty else {
print("Error: Name required")
return false
}
guard let userEmail = email, userEmail.contains("@") else {
print("Error: Valid email required")
return false
}
guard let userAge = age, userAge >= 13 else {
print("Error: Must be 13 or older")
return false
}
print("Welcome, \(userName)!")
return true
}
validateUser(name: nil, email: "[email protected]", age: 15)
validateUser(name: "Bob", email: "invalid", age: 15)
validateUser(name: "Alice", email: "[email protected]", age: 10)
validateUser(name: "Charlie", email: "[email protected]", age: 16)
// Challenge 6: Pattern with nested loops
print("\n--- Triangle Pattern ---")
for row in 1...5 {
var line = ""
for _ in 1...row {
line += "* "
}
print(line)
}Final Challenge!
Combine everything you've learned: Create a simple game that asks the player to guess numbers, validates input with guard, uses loops for multiple rounds, and keeps score!