Skip to main content

How to find the maximum number in a list using Kotlin

How to find the maximum number in a list using Kotlin.

Here is a step-by-step tutorial on how to find the maximum number in a list using Kotlin.

Step 1: Create a List

First, we need to create a list of numbers. You can either hardcode the values or take input from the user. Here's an example of creating a list of numbers:

val numbers = listOf(5, 7, 2, 10, 3)

Step 2: Initialize the Maximum Number

Next, we need to initialize a variable to store the maximum number found in the list. We can start by assigning it the first element of the list. Here's an example:

var maxNumber = numbers[0]

Step 3: Iterate through the List

Now, we need to iterate through the list and compare each element with the current maximum number. If we find a number greater than the current maximum, we update the value of the maxNumber variable. Here's an example of using a for loop to iterate through the list:

for (number in numbers) {
if (number > maxNumber) {
maxNumber = number
}
}

Step 4: Print the Maximum Number

Finally, we can print out the maximum number found in the list. Here's an example:

println("The maximum number is: $maxNumber")

Complete Example: Here's the complete example code that combines all the steps mentioned above:

fun main() {
val numbers = listOf(5, 7, 2, 10, 3)
var maxNumber = numbers[0]

for (number in numbers) {
if (number > maxNumber) {
maxNumber = number
}
}

println("The maximum number is: $maxNumber")
}

Output: When you run the above code, you will see the following output:

The maximum number is: 10

Congratulations! You have successfully found the maximum number in a list using Kotlin. Feel free to modify the code and try it with different sets of numbers.