English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to calculate the sum of natural numbers

Kotlin Examples Comprehensive

In this program, you will learn to use for loops and while loops in Kotlin to calculate the sum of natural numbers. You will also see how using range can help solve the problem.

Positive numbers1,2,3 ...are called natural numbers, and their sum starts from1The result of all numbers up to the given number.

The sum of natural numbers for n is:

1 + 2 + 3 + ... + n

Example1The sum of natural numbers using a for loop

fun main(args: Array<String>) {
    val num = 100
    var sum = 0
    for (i in 1to num) {
        // sum = sum+i;
        sum += i
    }
    println("Sum = $sum")
}

The output when running the program is:

Sum = 5050

The above program starts from1to the given num(100) loop, and add all numbers to the variable sum.

Unlike Java, in Kotlin, you can use range(1and in operators to loop through1to the number num.

This is the equivalent Java code:Java program to calculate the sum of natural numbers

You can also solve this problem using a while loop, as shown below:

Example2: Natural number sum using while loop

fun main(args: Array<String>) {
    val num = 50
    var i = 1
    var sum = 0
    while (i <= num) {
        sum += i
        i++
    }
    println("Sum = $sum")
}

The output when running the program is:

Sum = 1275

In the above program, unlike the for loop, we must increment the value of i inside the loop body.

Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (up to num) is known.

Kotlin Examples Comprehensive