Kotlin Program to find the sum of prime elements in an array


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


Array list: 3 4 5 6 7 8 9 10

Sum is => 3 + 5 + 7 = 15

Example: How to find the sum of 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
    var s=0
    val sc = Scanner(System.`in`)

    print("Enter 6 elements:")

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

    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) {
            s+=arr[i]
        }
    }

    println("Sum of Prime elements:$s")
}

Output:

Enter 6 elements:2 3 4 5 6 7
Sum of Prime elements:17