Anonymous Kotlin function: Calculate a factorial
Write an anonymous Kotlin function to calculate the factorial of a number.
Sample Solution:
Kotlin Code:
fun main() {
val number = 5
fun factorial(n: Int): Int {
return if (n <= 1) {
1
} else {
n * factorial(n - 1)
}
}
val result = factorial(number)
println("Factorial of $number is $result")
}
Sample Output:
Factorial of 5 is 120
Explanation:
In the above exercise -
The function "factorial()" takes an integer n as input and calculates the factorial using recursion.
Inside the "factorial()" function, we check if n is less than or equal to 1, and if so, we return 1. Otherwise, we calculate the factorial by multiplying n with the factorial of n - 1.
Kotlin Editor:
Previous: Check palindrome string.
Next: Find maximum element in array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics