Kotlin Program to find prime elements in an array


In this program, You will learn how to find prime elements in an array in Kotlin.


Array list: 3 4 5 6 7 8

Prime elements is: 3 5 7

Example: How to find prime elements in an array in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    val arr = IntArray(6)
    var p: Int
    var j: Int
    val sc = Scanner(System.`in`)

    print("Enter 6 elements:")

    for (i in 0 until arr.size) {
        arr[i] = sc.nextInt()
    }

    print("All Prime list are:")

    for (i in 0 until arr.size) {

        j = 2
        p = 1

        while (j < arr[i]) {
            if (arr[i] % j == 0) {
                p = 0
                break
            }
            j++
        }
        if (p == 1) {
            print("${arr[i]}  ")
        }
    }
}

Output:

Enter 6 elements:2 3 4 5 6 7
All Prime list are:2  3  5  7