In this kotlin programming example we will find largest element in the array from the given array. We are asking user to enter array elements and then find the largest element.
In this kotlin example we also create an Int Array with a fixed size.
Let's get started
Step 1: Create an Int Array with a size 5;
Step 2: Let's take inputs from user as integer with Scanner class
Step 3: Add user values into Int Array
Step 4: Now take one variable largestElement and assign its value from the array first index value
Step 5: Now loop the array to compare with largestElement
Step 6: Finally we will have the large number inside largestElement variable
Example code
import java.util.Scanner fun main() { var k:Int; var inputArray: IntArray =IntArray(5); val integer = Scanner(System.`in`) for( k in 0..4) { print("Enter an integer: ") var enteredinteger:Int = integer.nextInt() inputArray[k]=enteredinteger } var largestElement = inputArray[0] for (n in inputArray) { if (largestElement < n) largestElement = n } println("The largest element in the array is %d".format(largestElement)) } |
output:
Enter an integer: 12 Enter an integer: 1 Enter an integer: 25 Enter an integer: 23 Enter an integer: 129 The largest element in the array is 129 |
Conclusion: In this kotlin example we covered add elements to array fro user inputs and then find largest element form the array.
Article Contributed By :
|
|
|
|
841 Views |