Swift programming revision for Level 3
Goal
You are going to build a small Swift program that helps a student track how much money they spend on lunch in a week. This task revises loop and conditional structures, including the for loop, the while loop, and the if statement,
Part 1: Weekly lunch data
Copy this array into your program. These are the lunch costs for Monday to Friday.
let lunches = [6.50, 8.00, 5.75, 9.20, 7.10]
Part 2: Print each day’s spending (for loop)
Use a for loop to print the lunch cost for each day.
Loop through the lunches array. Print each day as Day 1, Day 2, and so on. Format the price with a $ sign.
Example output:
Day 1: $6.50
Day 2: $8.00
Day 3: $5.75
Day 4: $9.20
Day 5: $7.10
Part 3: Functions
Write these functions. Use them later to calculate totals, averages, and budget status.
Total cost function
This should return the total cost of all lunches.
func totalCost(prices: [Double]) -> Double
Budget check function
This should return true if the student spent more than the budget.
func isOverBudget(total: Double, budget: Double) -> Bool
Average cost function
This should return the average lunch cost per day.
func averageCost(prices: [Double]) -> Double
Part 4: Budget decision (if statement)
Set a weekly budget:
let budget = 35.00
After calculating the total lunch cost, make a budget decision.
If the student is under budget, print You stayed within budget. If the student is over budget, print Warning: You overspent this week.
Part 5: High spending day check (if inside loop)
Inside your for loop, add this check.
If any lunch costs more than $9.00, print High spending day detected.
Part 6: Snack spending simulation (while loop)
The student also buys snacks. Write a while loop that keeps adding snacks until snack spending reaches at least $10.
Start with snackTotal = 0. Each snack costs $2.50. After each snack purchase, print the running total.
Example output:
Snack total: $2.50
Snack total: $5.00
Snack total: $7.50
Snack total: $10.00
Part 7: Final summary output
At the end, print the weekly lunch total, weekly snack total, combined total, average daily lunch cost, and whether they stayed within budget.
Example format:
Lunch total: $36.55
Snack total: $10.00
Combined total: $46.55
Average lunch cost: $7.31
Warning: You overspent this week.
Extension for Super Players!
Write this function. It should find the most expensive lunch cost.
func mostExpensiveDay(prices: [Double]) -> Double
Print:
Most expensive lunch: $9.20