Write a Kotlin Program to Find Factorial of a Number

In Kotlin, we can calculate the factorial of a number using a recursive function or a loop.

Here, we will discuss both approaches.

Approach 1: Using a Recursive Function

A recursive function is a function that calls itself.

Here, we will define a function called “factorial” that takes a single parameter “n” and returns the factorial of that number.

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

In this function, we first check if the value of “n” is 0. If it is, we return 1 because the factorial of 0 is 1. If “n” is not 0, we multiply “n” with the result of calling the “factorial” function with “n-1” as the parameter.

Approach 2: Using a Loop

We can also calculate the factorial of a number using a loop. Here, we will use a for loop to calculate the factorial.

fun factorial(n: Int): Int {
    var result = 1
    for (i in 1..n) {
        result *= i
    }
    return result
}

In this function, we first initialize a variable called “result” to 1.

We then use a for loop to multiply the value of “result” with each number from 1 to “n”. After the loop, we return the value of “result”.

Testing the Functions

To test the functions, we can call them with a number and print the result.

fun main(args: Array<String>) {
    val number = 5
    val result = factorial(number)
    println("The factorial of $number is $result")
}

This will output “The factorial of 5 is 120” because 5! = 5 * 4 * 3 * 2 * 1 = 120.


Conclusion

In this blog post, we discussed two approaches to find the factorial of a number in Kotlin.

We learned how to use a recursive function and a loop to calculate the factorial.

We also wrote a program to test the functions and print the result.