ScripticXLearn programming visually
Platform
Problems
Community
Leaderboard
Learn
Docs
MiniScript+ basicsVariablesOperators and expressionsInput and outputConditions and decisionsLoopsStringsSums, counts, and extremaDigits of a numberDivisibility and prime numbersNumeric sequences and recurrencesNumber basesFunctions and parametersRecursion
Examples
Basic programsConditionsInput and outputLoopsAlgorithmsWorking with textDigit problemsBase conversionsFunctions and recursionEncode text with a key
What's newHelpContact
Loading…

Examples

MiniScript+

ExamplesMiniScript+
Fundamentals
Basic programsConditionsInput and output
Programming patterns
LoopsAlgorithmsWorking with textDigit problemsBase conversionsFunctions and recursionEncode text with a key
Examples/Functions and recursion

Functions and recursion

Reuse calculations, preserve local variables, and trace recursive calls.

On this page
Reuse a digit-sum calculationRecursive factorialTry it

Read functions and recursion first. Each block is a complete program that can be opened independently in the editor.

Reuse a digit-sum calculation#

MS+MiniScript+
1FUNCTION digitSum(n)2  total = 03  WHILE n > 04    total = total + n MOD 105    n = n DIV 106  END7  RETURN total8END9x = 407210PRINT digitSum(x)11PRINT digitSum(99)12PRINT x

The output is 13, 18, 4072. Parameter n changes inside the call without changing x. Each call owns its total. The function assumes a non-negative integer and correctly returns 0 for zero.

Recursive factorial#

MS+MiniScript+
1FUNCTION factorial(n)2  IF n == 0 THEN3    RETURN 14  END5  RETURN n * factorial(n - 1)6END7PRINT factorial(5)

The result is 120. Calls descend from 5 to 0; the base case returns 1, then each call multiplies the returned value by its own argument. Test 0 and 1: both have factorial 1.

The argument must be a non-negative integer. Do not run this example with negative or fractional arguments: they do not reach the base case. Execution has step and active-call limits; use small values. Large results also lose numeric precision.

Try it#

Add isPalindrome(n) returning a Boolean, using the numeric reversal example. Compare iterative and recursive versions of the sum from 1 through n. Use RETURN for a value needed in other calculations and PRINT for output.

PreviousBase conversionsNextEncode text with a key

On this page

Reuse a digit-sum calculationRecursive factorialTry it