Kotlin – Sum of Squares of First N Natural Numbers

Kotlin – Find Sum of Squares of First N Natural Numbers

In Kotlin, you can calculate the sum of the squares of the first N natural numbers using a loop and a simple formula. This tutorial will guide you through the process of writing a Kotlin program to find the sum of squares 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 of squares.

val n = 5 // Change the value of n as needed

Step 2: Calculate the Sum of Squares

Create a function to calculate the sum of squares of the first N natural numbers using a loop and the formula sum += i * i.

fun calculateSumOfSquares(n: Int): Int {
    var sum = 0
    for (i in 1..n) {
        sum += i * i
    }
    return sum
}

Step 3: Print the Result

Call the calculateSumOfSquares function with the value of N as the argument and print the result.

val sumOfSquares = calculateSumOfSquares(n)
println("Sum of squares of the first $n natural numbers is: $sumOfSquares")

Complete Kotlin Program

The following is the complete Kotlin program to find the sum of squares of the first N natural numbers.

Kotlin Program

fun main() {
    val n = 5 // Change the value of n as needed
    val sumOfSquares = calculateSumOfSquares(n)
    println("Sum of squares of the first $n natural numbers is: $sumOfSquares")
}

fun calculateSumOfSquares(n: Int): Int {
    var sum = 0
    for (i in 1..n) {
        sum += i * i
    }
    return sum
}

Output

Sum of squares of the first 5 natural numbers is: 55

Summary

By following these steps and using a loop to calculate the sum of squares, you can easily find the sum of squares of the first N natural numbers in Kotlin.