Kotlin – Sum of Cubes of First N Natural Numbers

Kotlin – Find Sum of Cubes of First N Natural Numbers

In Kotlin, you can calculate the sum of the cubes 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 the cubes 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 cubes.

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

Step 2: Calculate the Sum of Cubes

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

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

Step 3: Print the Result

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

val sumOfCubes = calculateSumOfCubes(n)
println("Sum of cubes of the first $n natural numbers is: $sumOfCubes")

Complete Kotlin Program

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

Kotlin Program

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

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

Output

Sum of cubes of the first 5 natural numbers is: 225

Summary

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