Kotlin – Find the Sum of First N Natural Numbers
In Kotlin, you can calculate the sum of the first N natural numbers using a simple formula. This tutorial will guide you through the process of writing a Kotlin program to find the sum of the first N natural numbers.
Example
Step 1: Define the Value of N
Start by defining the value of N, which represents the number of natural numbers for which you want to calculate the sum.
val n = 10 // Change the value of n as needed
Step 2: Calculate the Sum
Create a function to calculate the sum of the first N natural numbers using the formula n * (n + 1) / 2
.
fun calculateSum(n: Int): Int {
return n * (n + 1) / 2
}
Step 3: Print the Result
Call the calculateSum
function with the value of N as the argument and print the result.
val sum = calculateSum(n)
println("Sum of the first $n natural numbers is: $sum")
Complete Kotlin Program
The following is the complete Kotlin program to find the sum of the first N natural numbers.
Kotlin Program
fun main() {
val n = 10 // Change the value of n as needed
val sum = calculateSum(n)
println("Sum of the first $n natural numbers is: $sum")
}
fun calculateSum(n: Int): Int {
return n * (n + 1) / 2
}
Output
Sum of the first 10 natural numbers is: 55
Summary
By following these steps, you can easily calculate the sum of the first N natural numbers in Kotlin using a simple formula.