Kotlin Program to delete an element in an array
In this program, You will learn how to delete an element in an array in Kotlin.
Array list is: 2 3 4 5 6 7
Enter for delete: 4
New Array list is: 2 3 5 6 7
Example: How to delete an element in an array in Kotlin.
import java.util.Scanner
fun main(args: Array<String>) {
val arr = IntArray(100)
var n: Int
var num: Int
var p = 0
val sc = Scanner(System.`in`)
print("Enter size of an array:")
n = sc.nextInt()
print("Enter $n elements:")
for (i in 0 until n) {
arr[i] = sc.nextInt()
}
print("Enter a element for delete:")
num = sc.nextInt()
for (i in 0 until n) {
if (arr[i] == num) {
arr[i] = arr[i + 1]
p = 1
} else if (p > 0) {
arr[i] = arr[i + 1]
}
}
print("New Array list are:")
for (i in 0 until n - p)
print("${arr[i]} ")
}
Output:
Enter size of an array:5
Enter 5 elements:10 20 30 40 50
Enter a element for delete:20
New Array list are:10 30 40 50