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
numbers.first() // 10
To retrieve the last element of any set, we can use the
numbers.last() // 25
Finally, if we’d like to sum up all of the elements in a set, we can use the
numbers.sum() // 70
Note: To see the output of each function call on a set, it must be wrapped in a print statement.
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:
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 the
- Declare the variable,
numStudents, and within it store the result of using the
- Finally, declare the variable,
averageand assign it the division expression of
Lastly, set up a conditional that follows this logic:
- If the average grade is less than 65, then output the text,
- Otherwise, output the text,