English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to find the sum of natural numbers using recursion

Comprehensive Collection of Kotlin Examples

In this program, you will learn to use recursion in Kotlin to find the sum of natural numbers. This is done with the help of a recursive function.

Positive numbers1,2,3 ...are called natural numbers. The following program takes a positive integer from the user and calculates the sum of the given number.

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

Example: Using recursion to find the sum of natural numbers

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
}

When running the program, the output is:

Sum = 210

The numbers to be summed are stored in the variable number.

Initially, calling addNumbers() from the main() function and passing20 as the parameter.

and pass number(2) plus the result addNumbers(19) .

In the next function call from addNumbers() to addNumbers(), the following is passed:19, it is added to the result of addNumbers(18. This process continues until num equals 0.

When num equals 0, there is no recursive call, which will return the sum of integers to the main() function.

This is the equivalent Java code:Java Program Using Recursion to Find the Sum of Natural Numbers

Comprehensive Collection of Kotlin Examples