Lesson 10 â€ĸ Intermediate

Functions

25 minutes
Reusability

🔧 What are Functions?

Functions are reusable blocks of code that perform a specific task and return a value. They help you avoid repeating code and make your programs more organized and easier to maintain.

Visual: Function Call & Return Flow

📄
Main Program
result = Add(5, 3)
↓ Call →
âš™ī¸
Function: Add
Parameters:
a=5, b=3
Process:
sum = a + b
â†Šī¸
Return Value
8
← Back to Main
Why Use Functions?
  • DRY Principle: Don't Repeat Yourself - write once, use many times
  • Organization: Break complex problems into smaller pieces
  • Reusability: Use the same code in multiple places
  • Testing: Easier to test small functions than large programs
  • Collaboration: Team members can work on different functions

📐 Function Syntax

Function FunctionName(parameters)
    # Function code
    Return result
Endfunction

Calling a Function

var result = FunctionName(arguments)

Simple Function Example

Example: Basic Function
Algorithm FunctionDemo

# Define the function
Function AddNumbers(a, b)
    var sum = a + b
    Return sum
Endfunction

# Use the function
var result1 = AddNumbers(5, 3)
var result2 = AddNumbers(10, 20)

Print "5 + 3 =", result1
Print "10 + 20 =", result2

Endalgorithm
Output
5 + 3 = 8 10 + 20 = 30

📊 Functions with Parameters

Parameters are variables that receive values when the function is called.

No Parameters

Example: Function with No Parameters
Algorithm NoParamsExample

Function GetGreeting()
    Return "Hello, World!"
Endfunction

var message = GetGreeting()
Print message

Endalgorithm

One Parameter

Example: Function with One Parameter
Algorithm OneParamExample

Function Square(number)
    Return number * number
Endfunction

Print "Square of 5:", Square(5)
Print "Square of 12:", Square(12)

Endalgorithm

Multiple Parameters

Example: Function with Multiple Parameters
Algorithm MultipleParams

Function CalculateArea(length, width)
    Return length * width
Endfunction

Function CalculateVolume(length, width, height)
    Return length * width * height
Endfunction

var area = CalculateArea(5, 10)
var volume = CalculateVolume(5, 10, 3)

Print "Area:", area
Print "Volume:", volume

Endalgorithm

🔄 Return Values

Functions can return different types of values:

Example: Different Return Types
Algorithm ReturnTypes

# Returns a number
Function GetAge()
    Return 25
Endfunction

# Returns a string
Function GetName()
    Return "Alice"
Endfunction

# Returns a boolean
Function IsAdult(age)
    Return age >= 18
Endfunction

Print "Name:", GetName()
Print "Age:", GetAge()
Print "Is adult:", IsAdult(GetAge())

Endalgorithm

Real-World Examples

Temperature Converter

Example: Temperature Functions
Algorithm TemperatureConverter

# Convert Celsius to Fahrenheit
Function CelsiusToFahrenheit(celsius)
    Return celsius * 9 / 5 + 32
Endfunction

# Convert Fahrenheit to Celsius
Function FahrenheitToCelsius(fahrenheit)
    Return (fahrenheit - 32) * 5 / 9
Endfunction

Print "=== Temperature Converter ==="
Print ""

var tempC = Input "Enter temperature in Celsius:"
var tempF = CelsiusToFahrenheit(tempC)

Print tempC, "°C =", tempF, "°F"

Print ""
var tempF2 = Input "Enter temperature in Fahrenheit:"
var tempC2 = FahrenheitToCelsius(tempF2)

Print tempF2, "°F =", tempC2, "°C"

Endalgorithm

Grade Calculator

Example: Grade Functions
Algorithm GradeCalculator

# Calculate average of three scores
Function CalculateAverage(score1, score2, score3)
    var total = score1 + score2 + score3
    Return total / 3
Endfunction

# Get letter grade from numeric score
Function GetLetterGrade(score)
    If score >= 90 Then
        Return "A"
    Else If score >= 80 Then
        Return "B"
    Else If score >= 70 Then
        Return "C"
    Else If score >= 60 Then
        Return "D"
    Else
        Return "F"
    Endif
Endfunction

# Check if passing
Function IsPassing(score)
    Return score >= 60
Endfunction

# Main program
Print "=== Grade Calculator ==="
Print ""

var test1 = Input "Test 1 score:"
var test2 = Input "Test 2 score:"
var test3 = Input "Test 3 score:"

var average = CalculateAverage(test1, test2, test3)
var grade = GetLetterGrade(average)
var passing = IsPassing(average)

Print ""
Print "=== RESULTS ==="
Print "Average score:", average
Print "Letter grade:", grade
Print "Passing:", passing

Endalgorithm

Math Utilities

Example: Math Functions
Algorithm MathUtilities

# Check if number is even
Function IsEven(number)
    Return number mod 2 == 0
Endfunction

# Get absolute value
Function Abs(number)
    If number < 0 Then
        Return -number
    Else
        Return number
    Endif
Endfunction

# Get maximum of two numbers
Function Max(a, b)
    If a > b Then
        Return a
    Else
        Return b
    Endif
Endfunction

# Calculate factorial
Function Factorial(n)
    var result = 1
    For i = 1 To n
        result = result * i
    Endfor
    Return result
Endfunction

# Test the functions
Print "Is 10 even?", IsEven(10)
Print "Abs(-5):", Abs(-5)
Print "Max(15, 23):", Max(15, 23)
Print "5! =", Factorial(5)

Endalgorithm

Functions Calling Functions

Functions can call other functions!

Example: Nested Function Calls
Algorithm NestedFunctions

Function Add(a, b)
    Return a + b
Endfunction

Function Multiply(a, b)
    Return a * b
Endfunction

# This function uses other functions
Function CalculateTotal(price, quantity, taxRate)
    var subtotal = Multiply(price, quantity)
    var tax = Multiply(subtotal, taxRate)
    var total = Add(subtotal, tax)
    Return total
Endfunction

var finalPrice = CalculateTotal(19.99, 3, 0.08)
Print "Total price:", finalPrice

Endalgorithm

📋 Function Best Practices

Writing Good Functions
  • Single Purpose: Each function should do ONE thing well
  • Descriptive Names: Name should describe what the function does (CalculateArea, not DoStuff)
  • Keep it Short: If a function is too long, break it into smaller functions
  • Document: Add comments explaining what the function does
  • Consistent Returns: Always return the same type of value

Common Mistakes

Mistake 1: Forgetting Return

❌ Wrong:

Function Add(a, b)
    var sum = a + b
    # Forgot to return!
Endfunction

✅ Correct:

Function Add(a, b)
    var sum = a + b
    Return sum
Endfunction

Key Takeaways

  • ✅ Functions are reusable blocks of code that return values
  • ✅ Define with Function, close with Endfunction
  • ✅ Use Return to send a value back to the caller
  • ✅ Parameters let you pass data into functions
  • ✅ Functions can call other functions
  • ✅ Good functions do ONE thing well
  • ✅ Use descriptive names and add comments

đŸ’Ē Practice Exercises

Try These Exercises

Exercise 1: Circle Functions
Create functions to calculate circle area and circumference given radius. Use them in a program.
Exercise 2: Prime Checker
Write a function IsPrime(n) that returns true if n is prime, false otherwise. Test with multiple numbers.
Exercise 3: String Functions
Create functions: CountVowels(text), ReverseString(text), and IsPalindrome(text).
Exercise 4: BMI Calculator Functions
Create CalculateBMI(weight, height) and GetBMICategory(bmi) functions. Build a complete BMI program.
Fantastic Work!
You now understand how to create and use functions to make your code reusable! In the next lesson, we'll learn about procedures - functions that don't return values.