In this tutorial, you shall learn how to find the sum of first n natural numbers in Kotlin, using formula or a loop statement, with example programs.
Kotlin – Sum of first N natural numbers
To find the sum of first n natural numbers in Kotlin, we can use the formula or a looping statement.
The formula to find the sum of first n natural numbers is
n * ( n + 1 ) / 2
Program with Formula
In the following program, we read n
from user and find the sum of first n natural numbers using the specified formula.
Main.kt
fun main() {
print("Enter n : ")
val n = readLine()!!.toInt()
val sum = n * (n + 1) / 2
print("Sum of first $n natural numbers is $sum")
}
Output #1
Enter n : 10
Sum of first 10 natural numbers is 55
Output #2
Enter n : 500
Sum of first 500 natural numbers is 125250
Related tutorials for the above program
Program with Looping statement
In the following program, we read n
from user and find the sum of first n natural numbers using For loop statement.
Main.kt
fun main() {
print("Enter n : ")
val n = readLine()!!.toInt()
var sum = 0
for (i in 1..n) {
sum += i
}
print("Sum of first $n natural numbers is $sum")
}
Output #1
Enter n : 10
Sum of first 10 natural numbers is 55
Output #2
Enter n : 500
Sum of first 500 natural numbers is 125250
Related tutorials for the above program
Conclusion
In this Kotlin Tutorial, we learned how to find the sum of first n natural numbers.