Creating Functions
User-defined functions allow you to organize code into reusable blocks, making your programs cleaner, more maintainable, and easier to understand.
Basic Function Syntax
Section titled “Basic Function Syntax”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”Early Return
Section titled “Early Return”Exit a function before reaching the end:
function isAdult takes in age { if age >= 18 return true else return false}
// Simplified versionfunction isAdult takes in age { if age >= 18 return true return false}Multiple Return Points
Section titled “Multiple Return Points”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"Return Multiple Values
Section titled “Return Multiple Values”Return an array with multiple values:
function divideWithRemainder takes in dividend and divisor { quotient = floor(dividend / divisor) remainder = dividend % divisor return [quotient, remainder]}
result = divideWithRemainder(17, 5)output "Quotient: {result[0]}" // 3output "Remainder: {result[1]}" // 2Function Examples
Section titled “Function Examples”Temperature Converter
Section titled “Temperature Converter”function celsiusToFahrenheit takes in celsius fahrenheit = (celsius * 9/5) + 32 return fahrenheit
function fahrenheitToCelsius takes in fahrenheit celsius = (fahrenheit - 32) * 5/9 return celsius
// Usagetemp1 = celsiusToFahrenheit(25)output "25°C = {temp1}°F"
temp2 = fahrenheitToCelsius(77)output "77°F = {temp2}°C"Circle Calculations
Section titled “Circle Calculations”constant PI = 3.14159
function circleArea takes in radius return PI * radius ^ 2
function circleCircumference takes in radius return 2 * PI * radius
function circleDiameter takes in radius return 2 * radius
// Usageradius = 5output "Radius: {radius}"output "Area: {circleArea(radius)}"output "Circumference: {circleCircumference(radius)}"output "Diameter: {circleDiameter(radius)}"String Utilities
Section titled “String Utilities”function reverse takes in text { reversed = "" for i from length of text - 1 to 0 reversed = reversed text[i] return reversed}
function isPalindrome takes in text { text = text to lowercase reversed = reverse(text) return text equals reversed}
function countVowels takes in text { vowels = "aeiouAEIOU" count = 0 for i from 0 to length of text - 1 { if text[i] is in vowels count++ } return count}
// Usageword = "racecar"output "'{word}' reversed: {reverse(word)}"output "Is palindrome: {isPalindrome(word)}"output "Vowel count: {countVowels(word)}"Array Operations
Section titled “Array Operations”function sum takes in array { total = 0 for each value in array total += value return total}
function average takes in array { if length of array equals 0 return 0 total = sum(array) return total / length of array}
function maximum takes in array { if length of array equals 0 return null max = array[0] for each value in array if value > max max = value return max}
function minimum takes in array { if length of array equals 0 return null min = array[0] for each value in array if value < min min = value return min}
// Usagenumbers = [23, 45, 12, 67, 34, 89, 15]output "Sum: {sum(numbers)}"output "Average: {average(numbers)}"output "Max: {maximum(numbers)}"output "Min: {minimum(numbers)}"Validation Functions
Section titled “Validation Functions”function isValidEmail takes in email { if length of email < 3 return false if NOT email contains "@" return false if NOT email contains "." return false return true}
function isValidAge takes in age { if NOT is number(age) return false if age < 0 OR age > 150 return false return true}
function isValidPassword takes in password { if length of password < 8 return false // Additional checks could go here return true}
// Usageemail = "user@example.com"if isValidEmail(email) output "Valid email"else output "Invalid email"Recursive Functions
Section titled “Recursive Functions”Functions that call themselves:
Factorial
Section titled “Factorial”function factorial takes in n if n <= 1 return 1 return n * factorial(n - 1)
// Usageoutput "5! = {factorial(5)}" // 120Fibonacci Sequence
Section titled “Fibonacci Sequence”function fibonacci takes in n if n <= 1 return n return fibonacci(n - 1) + fibonacci(n - 2)
// Usageoutput "Fibonacci(10) = {fibonacci(10)}" // 55Power Function
Section titled “Power Function”function power takes in base and exponent if exponent equals 0 return 1 if exponent equals 1 return base return base * power(base, exponent - 1)
// Usageoutput "2^8 = {power(2, 8)}" // 256Countdown
Section titled “Countdown”function countdown takes in n { if n <= 0 { output "Blast off!" return } output n countdown(n - 1)}
// Usagecountdown(5)// Output:// 5// 4// 3// 2// 1// Blast off!Functions with Default Behavior
Section titled “Functions with Default Behavior”While Common Pseudocode doesn’t have default parameters, you can handle missing values:
function greet takes in name and greeting { if greeting equals null OR greeting equals "" greeting = "Hello"
output "{greeting}, {name}!"}
// Usagegreet("Alice", "Hi") // Hi, Alice!greet("Bob", "") // Hello, Bob!Higher-Order Functions
Section titled “Higher-Order Functions”Functions that work with other functions:
function applyOperation takes in array and operation { result = [] for each value in array { newValue = operation(value) append newValue to result } return result}
function double takes in n return n * 2
function square takes in n return n * n
// Usagenumbers = [1, 2, 3, 4, 5]doubled = applyOperation(numbers, double)squared = applyOperation(numbers, square)Helper Functions
Section titled “Helper Functions”Break complex tasks into smaller functions:
function isLeapYear takes in year { if year % 4 != 0 return false if year % 100 != 0 return true if year % 400 == 0 return true return false}
function getDaysInMonth takes in month and year { // April, June, September, November have 30 days if month equals 4 OR month equals 6 OR month equals 9 OR month equals 11 return 30
// February if month equals 2 { if isLeapYear(year) return 29 return 28 }
// All other months have 31 days return 31}
function isValidDate takes in day and month and year { if month < 1 OR month > 12 return false
maxDays = getDaysInMonth(month, year) if day < 1 OR day > maxDays return false
return true}
// Usageif isValidDate(29, 2, 2024) output "Valid date"else output "Invalid date"Function Documentation
Section titled “Function Documentation”Add comments to explain what functions do:
// Calculates the area of a triangle using base and height// Parameters:// base: the length of the triangle's base// height: the height of the triangle// Returns: the area of the trianglefunction triangleArea takes in base and height return (base * height) / 2
// Checks if a number is prime// Parameters:// n: the number to check// Returns: true if prime, false otherwisefunction isPrime takes in n { if n <= 1 return false
for i from 2 to sqrt of n if n % i equals 0 return false
return true}Complete Example: Student Grade System
Section titled “Complete Example: Student Grade System”function calculateAverage takes in grades { if length of grades equals 0 return 0 sum = 0 for each grade in grades sum += grade return sum / length of grades}
function getLetterGrade takes in average if average >= 90 return "A" else if average >= 80 return "B" else if average >= 70 return "C" else if average >= 60 return "D" return "F"
function displayStudentReport takes in name and grades { avg = calculateAverage(grades) letter = getLetterGrade(avg)
output "===== Student Report =====" output "Name: {name}" output "Grades: " for i from 0 to length of grades - 1 output " Test {i + 1}: {grades[i]}" output "Average: {avg}" output "Letter Grade: {letter}" output "=========================="}
function isPassingStudent takes in average return average >= 60
// Main programstudentName = "Alice Johnson"studentGrades = [85, 92, 78, 88, 95]
displayStudentReport(studentName, studentGrades)
avg = calculateAverage(studentGrades)if isPassingStudent(avg) output "Status: PASSING"else output "Status: FAILING"Best Practices
Section titled “Best Practices”1. One Purpose Per Function
Section titled “1. One Purpose Per Function”// Bad - does too muchfunction processUserAndSendEmail takes in user { validateUser(user) saveToDatabase(user) sendWelcomeEmail(user) updateStatistics()}
// Good - separate functionsfunction validateUser takes in user // validation only
function saveUser takes in user // saving only
function sendWelcomeEmail takes in user // email only2. Use Descriptive Names
Section titled “2. Use Descriptive Names”// Badfunction calc takes in x and y return x * y
// Goodfunction calculateRectangleArea takes in width and height return width * height3. Keep Functions Short
Section titled “3. Keep Functions Short”// A function should do one thing well// If it's too long, break it into smaller functionsfunction processOrder takes in order { validateOrder(order) calculateTotal(order) applyDiscounts(order) processPayment(order) sendConfirmation(order)}4. Avoid Side Effects
Section titled “4. Avoid Side Effects”// Bad - modifies global variabletotal = 0function add takes in value total = total + value
// Good - returns a valuefunction add takes in current and value return current + value
total = add(total, 5)5. Validate Parameters
Section titled “5. Validate Parameters”function divide takes in numerator and denominator { if denominator equals 0 { output "Error: Division by zero" return null }
return numerator / denominator}6. Return Early
Section titled “6. Return Early”function processValue takes in value { // Check invalid cases first if value equals null return null
if value < 0 return 0
// Main logic return value * 2}Function Scope
Section titled “Function Scope”Variables declared inside functions are local to that function:
globalVar = 10
function testScope takes in param { localVar = 20 output "Inside function:" output " param: {param}" output " localVar: {localVar}" output " globalVar: {globalVar}"}
testScope(5)// Can't access localVar or param here// Can access globalVarCommon Mistakes to Avoid
Section titled “Common Mistakes to Avoid”1. Forgetting to Return a Value
Section titled “1. Forgetting to Return a Value”// Bad - no return statementfunction add takes in a and b sum = a + b // Oops, forgot to return!
// Goodfunction add takes in a and b return a + b2. Modifying Parameters Unintentionally
Section titled “2. Modifying Parameters Unintentionally”// Be careful with arrays and objectsfunction clearArray takes in arr { arr = [] // This doesn't clear the original array!}
// Better approachfunction clearArray takes in arr { while length of arr > 0 remove element at index 0 from arr}3. Recursive Functions Without Base Cases
Section titled “3. Recursive Functions Without Base Cases”// Bad - infinite recursion!function badRecursion takes in n return badRecursion(n - 1)
// Good - has base casefunction goodRecursion takes in n if n <= 0 return 0 return n + goodRecursion(n - 1)When to Create Functions
Section titled “When to Create Functions”Create a function when:
- Code is repeated - If you write the same code twice, make it a function
- Complex logic - Break down complicated operations into smaller, named functions
- Reusability - Code that might be used in multiple places
- Testing - Isolated functions are easier to test
- Readability - Named functions make code self-documenting
// Instead of repeating this:if username equals "" OR length of username < 3 output "Invalid username"
// Create a function:function isValidUsername takes in username if username equals "" OR length of username < 3 return false return true
if NOT isValidUsername(username) output "Invalid username"