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.
Basic Function
Section titled “Basic Function”A function that returns a value:
function hello takes in nothing return "world"Or simply:
function hello return "world"Functions with Parameters
Section titled “Functions with Parameters”Single Parameter
Section titled “Single Parameter”function square takes in number return number * number
result = square(5) // Returns 25Multiple Parameters
Section titled “Multiple Parameters”function add takes in num1 and num2 return num1 + num2
sum = add(10, 20) // Returns 30Three or More Parameters
Section titled “Three or More Parameters”function calculateVolume takes in length and width and height volume = length * width * height return volume
volume = calculateVolume(5, 3, 2) // Returns 30Calling Functions
Section titled “Calling Functions”Standard Syntax
Section titled “Standard Syntax”result = functionName(arg1, arg2)Natural Language Syntax
Section titled “Natural Language Syntax”result = run functionName with arg1 and arg2Example
Section titled “Example”function multiply takes in a and b return a * b
// Both ways workresult1 = multiply(5, 3)result2 = run multiply with 5 and 3Procedures (No Return Value)
Section titled “Procedures (No Return Value)”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 procedureprintGreeting("Alice")/* Output: Hello, Alice! Welcome to the program! */Return Statements
Section titled “Return Statements”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"Simple Example
Section titled “Simple Example”function calculateArea takes in width and height return width * height
function calculatePerimeter takes in width and height return 2 * (width + height)
// Usagew = 10h = 5output "Area: {calculateArea(w, h)}"output "Perimeter: {calculatePerimeter(w, h)}"