Skip to content

Functions and Procedures

Functions allow you to organize code into reusable blocks that can be called from different parts of your program. They’re essential for writing clean, maintainable code.

A function that returns a value:

function hello takes in nothing
return "world"

Or simply:

function hello
return "world"
function square takes in number
return number * number
result = square(5) // Returns 25
function add takes in num1 and num2
return num1 + num2
sum = add(10, 20) // Returns 30
function calculateVolume takes in length and width and height
volume = length * width * height
return volume
volume = calculateVolume(5, 3, 2) // Returns 30
result = functionName(arg1, arg2)
result = run functionName with arg1 and arg2
function multiply takes in a and b
return a * b
// Both ways work
result1 = multiply(5, 3)
result2 = run multiply with 5 and 3

Functions that perform actions but don’t return a value:

function printGreeting takes in name {
output "Hello, {name}!"
output "Welcome to the program!"
}
// Call the procedure
printGreeting("Alice")
/* Output:
Hello, Alice!
Welcome to the program! */

Functions can return values using the return keyword:

function isAdult takes in age {
if age >= 18
return true
return false
}
function getGrade takes in score
if score >= 90
return "A"
else if score >= 80
return "B"
else if score >= 70
return "C"
else if score >= 60
return "D"
return "F"
function calculateArea takes in width and height
return width * height
function calculatePerimeter takes in width and height
return 2 * (width + height)
// Usage
w = 10
h = 5
output "Area: {calculateArea(w, h)}"
output "Perimeter: {calculatePerimeter(w, h)}"