Write a Kotlin Program to Calculate the Sum of Natural Numbers

In Kotlin, you can calculate the sum of natural numbers using a loop. A natural number is a positive integer (1, 2, 3, …).

To calculate the sum of natural numbers, you can use a for loop or a while loop. Here’s an example of using a for loop:

fun main() {
    val n = 10
    var sum = 0

    for (i in 1..n) {
        sum += i
    }

    println("The sum of the first $n natural numbers is $sum")
}

In this example, we have initialized the value of n to 10, which means we want to calculate the sum of the first 10 natural numbers.

We have also initialized the value of sum to 0, which we will update in the loop.

The for loop starts with i equal to 1 and iterates up to n (inclusive) using the range expression 1..n. In each iteration, we add i to sum.

Finally, we print the result using the println function.

Here’s an example of using a while loop to calculate the sum of the first n natural numbers:

fun main() {
    val n = 10
    var sum = 0
    var i = 1

    while (i <= n) {
        sum += i
        i++
    }

    println("The sum of the first $n natural numbers is $sum")
}

In this example, we have initialized the value of i to 1, which we will use to iterate through the natural numbers.

The while loop continues to iterate as long as i is less than or equal to n. In each iteration, we add i to sum and increment i. Finally, we print the result using the println function.

Both of these approaches are valid ways to calculate the sum of natural numbers in Kotlin.

You can choose whichever one you prefer based on your coding style and the requirements of your program.