Recursivity
ufLang supports recursivity:
fun factorial(n)
{
if (n == 0)
return 1; // Base case: factorial of 0 is 1
return n * factorial(n - 1); // Recursive step: n * factorial of (n - 1)
}
var number : Int = 5;
var result : Int = factorial(number);
println(result); // Prints the result of factorial(5), which is 120
Explanation:
Recursive function (
factorial):The function takes an integer
nand returns the factorial ofn.If
nis0, it returns1(base case).Otherwise, it calls itself with
n - 1and multiplies the result byn(recursive step).
Main function:
We set a number (
5in this case) and calculate its factorial by calling thefactorialfunction.Finally, it prints the result, which will be
120(i.e., 5 * 4 * 3 * 2 * 1).
Last updated