Skip to content

Basic Programs Kotlin

Find first 10 ODD EVEN Numbers

fun main() {
    println("First 10 ODD Numbers:")
    printOddNumbers(10)
    
    println("\nFirst 10 EVEN Numbers:")
    printEvenNumbers(10)
}

fun printOddNumbers(limit: Int) {
    var count = 0
    var number = 1
    while (count < limit) {
        if (number % 2 != 0) {
            println(number)
            count++
        }
        number++
    }
}

fun printEvenNumbers(limit: Int) {
    var count = 0
    var number = 1
    while (count < limit) {
        if (number % 2 == 0) {
            println(number)
            count++
        }
        number++
    }
}

Output

First 10 ODD Numbers:
1
3
5
7
9
11
13
15
17
19

First 10 EVEN Numbers:
2
4
6
8
10
12
14
16
18
20

Find Prime Number

/**
Prime number*/
fun main() {
print("Enter a number: ")
val number = 11

if (isPrime(number)) {
    println("$number is a prime number.")
} else {
    println("$number is not a prime number.")
}

}

fun isPrime(num: Int): Boolean {
if (num <= 1) return false
if (num == 2) return true // 2 is a prime number
if (num % 2 == 0) return false // exclude even numbers greater than 2

for (i in 3..Math.sqrt(num.toDouble()).toInt() step 2) {
    if (num % i == 0) return false
}

return true

}

Output

Enter a number: 11 is a prime number.