Menu
Coddy logo textTech

Total And Average

Part of the Fundamentals section of Coddy's Swift journey — lesson 81 of 86.

challenge icon

Challenge

Easy

In the previous lesson, you implemented the "View all expenses" feature. Now, implement the "Show total and average" feature for option "3".

Modify your code to handle option "3":

  1. When the user enters "3", check if the expenses array is empty
  2. If the array is empty, print No expenses to calculate.
  3. If the array has expenses, calculate and display:
    • The total of all expenses, formatted as Total: $X.X
    • The average expense, formatted as Average: $X.X
  4. Option "4" should still print Coming soon...
  5. Options "1", "2", and "5" should continue working as before

Hint: Use reduce(0, +) to calculate the total, and divide by Double(expenses.count) for the average.

Expected behavior:

  • When "3" is entered with no expenses, print No expenses to calculate.
  • When "3" is entered with expenses, print the total on one line and the average on the next line

Example interaction:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
3
No expenses to calculate.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
20.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
30.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
3
Total: $50.0
Average: $25.0
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!

Try it yourself

// Daily Expense Tracker - Menu Display

var expenses: [Double] = []

while true {
    // TODO: Write your code below to print the menu options
    // Each option should be on its own line with the format: "number. option text"
    print("1. Add expense")
    print("2. View all expenses")
    print("3. Show total and average")
    print("4. Clear all expenses")
    print("5. Exit")
    
    let choice = readLine()
    
    if choice == "1" {
        print("Enter expense amount:")
        if let input = readLine(), let amount = Double(input) {
            expenses.append(amount)
            print("Expense added!")
        }
    } else if choice == "2" {
        if expenses.isEmpty {
            print("No expenses recorded.")
        } else {
            print("Your expenses:")
            for expense in expenses {
                print("- $\(expense)")
            }
        }
    } else if choice == "3" {
        print("Coming soon...")
    } else if choice == "4" {
        print("Coming soon...")
    } else if choice == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

All lessons in Fundamentals