Start learning free

LESSON 145 OF 415 · LOOPS & GLOBAL VARIABLES

Student Grades in Swift: Average with a Loop and Double

Practice Read the full explanation

Given the grades of a student as an array, determine if the student has passed the class.

A Student has passed the class if the average of grades is 5 or more.

The average is defined as (grades[0] + grades[1] + ... + grades[n - 1]) / n

Example 1:

Input: grades = [4, 7, 5, 9, 8, 2]
Output: true
Explanation:
average = (4 + 7 + 5 + 9 + 8 + 2) / 6 =
= 35 / 6 = 5.833333333... >= 5

Example 2:

Input: grades = [4, 7, 5, 3, 8, 2]
Output: false
Explanation:
average = (4 + 7 + 5 + 3 + 8 + 2) / 6 =
= 29 / 6 = 4.83333.. < 5

Hints:

The problem can be broken in 3 steps:
1. Compute the sum of the array
2. Compute the average by dividing the sum by the length of the array
3. Decide the result based on the average being greater than or equal to 5
Let's start with step 1: How can we compute the sum of the array?

First of all, we should store this sum somewhere as we compute it. That 'somewhere' is a variable, let's name it sum. We have to iterate through every element of grades and add its value to sum. How can we achieve this?

With a loop! Let's use a for loop and a variable grade to iterate through the elements:
sum = 0
for each grade in grades:
	sum += grade
When the loop terminates, we know the sum. What should we do next?

We should compute average = sum / length and return average >= 5:
sum = 0
for each grade in grades:
	sum += grade
average = sum / length
return average >= 5


We have a for loop that performs exactly n iterations (n is the length of grades), thus the Time Complexity is O(n).
The only extra space we use are the variables sum, average and the iterator variable grade inside the loop, thus the Extra Space used is O(1).
STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · LOOPS & GLOBAL VARIABLES

    Student Grades in Swift, explained

    Problem overview

    The method hasPassed receives an array of integer grades and returns a Bool: true when the average grade is 5 or more, false otherwise. The average is the sum of the grades divided by how many there are.

    For [4, 7, 5, 9, 8, 2] the sum is 35 and the average is 35 / 6, about 5.83, so the answer is true. For [4, 7, 5, 3, 8, 2] the sum is 29 and the average is about 4.83, so the answer is false.

    Approach: sum, divide, compare

    The problem splits into three parts: add up the grades with a loop, divide by the count, and compare the result with 5. The loop uses a running total, the same pattern as any sum.

    The one real decision is the number type. If the sum and the division were done in Int, the division would truncate: 29 / 6 is 4. For non-negative grades the comparison with 5 would still come out the same, but the value would no longer be the average the task defines. Using Double keeps the fractional part, so the code computes the real average and compares that.

    Step by step

    1. Declare the total as a Double. var sum = 0.0 is a variable, since it grows, and the literal 0.0 makes Swift infer Double.
    2. Loop over the grades with for grade in grades.
    3. Add each grade, converted. sum += Double(grade). Swift never mixes number types implicitly, so the Int has to be converted first.
    4. Compute the average. A constant fits, since it is set once: let average = sum / Double(grades.count). The count is an Int, so it needs the same conversion.
    5. Return the comparison. average >= 5 is already a Bool, so no if is needed.

    The solution in Swift

    class Solution {
        func hasPassed(_ grades: [Int]) -> Bool {
            var sum = 0.0
            for grade in grades {
                sum += Double(grade)
            }
            let average = sum / Double(grades.count)
            return average >= 5
        }
    }
    

    Swift details worth knowing:

    • No implicit conversion. Writing sum += grade with a Double sum and an Int grade is a compile error: Swift cannot convert a value of type Int to the expected argument type Double.
    • Integer division truncates. 29 / 6 in Int is 4. The solution avoids this by dividing two Double values.
    • Literals adapt. In average >= 5 the literal 5 becomes a Double automatically, because literals take the type their context needs. Only variables and constants with a fixed type need explicit conversion.
    • let for values set once. average never changes after its declaration, so let is the idiomatic choice.

    Complexity

    Time: O(n), where n is the number of grades. The loop visits each grade once, and the division and comparison are constant work.

    Space: O(1). The function keeps sum, average and the loop variable.

    Edge cases and common mistakes

    • Exactly 5. [5, 5] has an average of 5.0 and returns true, because the comparison is >=.
    • Empty array. The sum is 0.0 and the count is 0.0, so the division gives nan (not a number). Every comparison with nan is false, so the function returns false without crashing. Integer division by zero, in contrast, would crash.
    • Dividing as integers. Summing in an Int and dividing by grades.count gives 4 for 4.83. The pass or fail answer happens to agree for non-negative grades, but the code stops computing the average the task defines.
    • Using >. That fails the "5 or more" rule for an average of exactly 5.
    • Forgetting the count conversion. sum / grades.count mixes Double and Int and does not compile.

    Testing

    • [4, 7, 5, 9, 8, 2] gives true.
    • [4, 7, 5, 3, 8, 2] gives false.
    • [5, 5] gives true.
    • [] gives false.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free