Write a Kotlin Program to Find the Sum of Natural Numbers using Recursion

In Kotlin, we can use recursion to find the sum of natural numbers.

Recursion is a technique in which a function calls itself until a specific condition is met.

In this case, the function will call itself until the sum of all natural numbers is calculated.

To calculate the sum of natural numbers, we can define a function called sumOfNaturalNumbers that takes a single parameter n, representing the last number in the natural number sequence to be summed.

The function should return the sum of all natural numbers from 1 to n.

Here’s the Kotlin program that uses recursion to find the sum of natural numbers:

fun sumOfNaturalNumbers(n: Int): Int {
    if (n == 1) {
        return 1
    }
    return n + sumOfNaturalNumbers(n - 1)
}

fun main() {
    val n = 10
    val sum = sumOfNaturalNumbers(n)
    println("Sum of natural numbers from 1 to $n is $sum")
}

In the above program, the sumOfNaturalNumbers function takes an integer n as input and returns an integer as output.

If n is equal to 1, the function returns 1, which is the base case.

If n is greater than 1, the function calls itself with n – 1 as the input and returns the sum of n and the result of the recursive call. This continues until the base case is reached.

In the main function, we call the sumOfNaturalNumbers function with n = 10, which will calculate the sum of natural numbers from 1 to 10.

The result is stored in the sum variable and printed to the console using println.

Recursion is a powerful technique that can be used to solve a wide range of problems.

By understanding how recursion works, you can write efficient and elegant code in Kotlin and other programming languages.