In addition to adding and removing elements from a set, the set collection supports a myriad of other functionalities. You can find the entire list in Kotlin’s documentation.
In this exercise, we’ll explore some of the most common set functions using the following example:
var numbers = setOf(10, 15, 20, 25)
To retrieve, the first element of any set, we can use the first()
function:
numbers.first() // 10
To retrieve the last element of any set, we can use the last()
function:
numbers.last() // 25
Finally, if we’d like to sum up all of the elements in a set, we can use the sum()
function:
numbers.sum() // 70
Note: To see the output of each function call on a set, it must be wrapped in a print statement.
Instructions
In Midterm.kt, we’ll write a program that determines if a class has failed or passed a midterm.
First let’s gather the grades, and store them in a mutable set, testGrades
, with the following numerical values:
65
50
72
80
53
84
Next, we’ll utilize the following formula to declare 3 variables that we’ll use to calculate the average:
- First, declare the variable,
sum
, and within it store the result of calling thesum()
function ontestGrades
. - Declare the variable,
numStudents
, and within it store the result of using thesize
property ontestGrades
. - Finally, declare the variable,
average
and assign it the division expression ofsum
divided bynumStudents
.
Lastly, set up a conditional that follows this logic:
- If the average grade is less than 65, then output the text,
"Failed"
. - Otherwise, output the text,
"Passed"
.