Kotlin Recursion function

A recursive function is a function that calls itself in its own definition. 

Let’s look at an example of a simple recursive function to calculate the factorial of a number:

fun factorial(n: Int): Int {
    return if (n == 0 || n == 1) {
        1
    } else {
        n * factorial(n - 1)
    }
}

// calling factorial function in main function
fun main() {
    val number = 5
    val result = factorial(number)
    println("Factorial of $number is $result")  // Output: Factorial of 5 is 120
}

When you call factorial(5), the recursive calls break down as follows:

factorial(5) = 5 * factorial(4)
            = 5 * 4 * factorial(3)
            = 5 * 4 * 3 * factorial(2)
            = 5 * 4 * 3 * 2 * factorial(1)
            = 5 * 4 * 3 * 2 * 1 = 120

The function repeatedly calls itself with smaller values until it reaches the base case, and then it starts returning the values back up the call stack to calculate the final result.

it’s essential to ensure that recursive functions have well-defined base cases to avoid infinite recursion.

Recursion is a useful technique for solving a variety of problems, such as traversing data structures like trees and graphs, searching, and more.