Kotlin recursive function: Find the smallest element in an array
Kotlin Function: Exercise-4 with Solution
Write a Kotlin recursive function to find the smallest element in an array.
Sample Solution:
Kotlin Code:
import java.util.Arrays
fun findSmallestElement(array: IntArray, index: Int = 0, smallest: Int = Int.MAX_VALUE): Int {
return if (index == array.size) {
smallest
} else {
val currentElement = array[index]
val updatedSmallest = if (currentElement < smallest) currentElement else smallest
findSmallestElement(array, index + 1, updatedSmallest)
}
}
fun main() {
val array = intArrayOf(7, 3, 8, -1, 0, 4)
val smallest = findSmallestElement(array)
println("Original array elements: ")
println(Arrays.toString(array))
println("Smallest element in the said array: $smallest")
}
Sample Output:
Original array elements: [7, 3, 8, -1, 0, 4] Smallest element in the said array: -1
Explanation:
In the function "findSmallestElement()", we pass an array, an initial index of 0, and a variable smallest to keep track of the current smallest element. At each recursive call, we check if the index is equal to the array size. If it is, we return the current smallest element. Otherwise, we compare the element at the current index with the smallest value. If the current element is smaller, we update the smallest value. We then make a recursive call with the incremented index and the updated smallest value. We continue this process until we get to the end of the array, where we get the smallest element.
Kotlin Editor:
Previous: Calculate the sum of array elements.
Next: Generate permutations of a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics