kotlin factorial
To calculate the factorial of a number in Kotlin, you can use a recursive function. Here is an example:
fun factorial(n: Int): Int {
return if (n == 0) {
1
} else {
n * factorial(n - 1)
}
}
fun main() {
val number = 5
val result = factorial(number)
println("The factorial of $number is $result.")
}
Explanation of each step:
1. We define a function called factorial
that takes an integer n
as input and returns an integer as output.
2. Inside the function, we use an if
statement to check if n
is equal to 0. If it is, we return 1 because the factorial of 0 is 1.
3. If n
is not equal to 0, we use recursion to calculate the factorial. We multiply n
with the factorial of n-1
and return the result.
4. In the main
function, we declare a variable called number
and assign it the value of 5.
5. We call the factorial
function with number
as the argument and assign the result to a variable called result
.
6. Finally, we use println
to display the calculated factorial by concatenating the values of number
and result
.