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
n
and returns the factorial ofn
.If
n
is0
, it returns1
(base case).Otherwise, it calls itself with
n - 1
and multiplies the result byn
(recursive step).
Main function:
We set a number (
5
in this case) and calculate its factorial by calling thefactorial
function.Finally, it prints the result, which will be
120
(i.e., 5 * 4 * 3 * 2 * 1).
Last updated