Kotlin Program to Find the Sum of Natural Numbers using Recursion

Kotlin Program to Find the Sum of Natural Numbers using Recursion: The positive numbers 1, 2, 3… are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.

You can find the sum of natural numbers using the loop as well. However, you will learn to solve this problem using recursion here.

Kotlin Program to Find the Sum of Natural Numbers using Recursion

Source Code

fun main(args: Array<String>) {
    val number = 20
    val sum = addNumbers(number)
    println("Sum = $sum")
}

fun addNumbers(num: Int): Int {
    if (num != 0)
        return num + addNumbers(num - 1)
    else
        return num
}

Output