English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to find the largest element in an array using a for loop in Kotlin.
fun main(args: Array<String>) { val numArray = doubleArrayOf(23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5) var largest = numArray[0] for (num in numArray) { if (largest < num) largest = num } println("Largest Element = %."2f".format(largest)) }
The output when running the program is:
Largest Element = 55.50
In the above program, we store the first element of the array in the variable largest.
Then, compare largest with other elements in the array. If any number is greater than largest, assign that number number to largest.
Thus, the largest number will be stored in the variable largest, and the final output will print this largest number.
This is the equivalent Java code:Java Program to Find the Largest Element in an Array