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:

  1. Recursive function (factorial):

    • The function takes an integer n and returns the factorial of n.

    • If n is 0, it returns 1 (base case).

    • Otherwise, it calls itself with n - 1 and multiplies the result by n (recursive step).

  2. Main function:

    • We set a number (5 in this case) and calculate its factorial by calling the factorial function.

    • Finally, it prints the result, which will be 120 (i.e., 5 * 4 * 3 * 2 * 1).

Last updated