AP Computer Science Principles

Unit 3.3 — Procedures and Functions

Defining, Calling, Returning Values, Parameters, and Modular Design

Student Note

In programming, procedures and functions help us organize code into smaller sections. Instead of writing the same code over and over again, we can create a procedure or function and use it whenever we need it.

This makes programs easier to read, easier to fix, and easier to reuse.

1. What Is a Procedure?

A procedure is a named group of programming instructions that performs a task.

Think of a procedure like a recipe. Once the recipe is written, you can use it whenever you want.

Example

PROCEDURE sayHello()
{
    DISPLAY("Hello!")
}

This procedure is named sayHello. It displays:

Hello!

2. Why Do Programmers Use Procedures?

Programmers use procedures to:

3. Defining a Procedure

Defining a procedure means creating it.

When you define a procedure, you give it:

  1. A name
  2. Optional parameters
  3. Instructions to run

Example

PROCEDURE greetUser()
{
    DISPLAY("Welcome to the program!")
}

This defines a procedure named greetUser.

Important: Defining a procedure does not automatically run it.

4. Calling a Procedure

Calling a procedure means using it or running it.

Example

greetUser()

When this line runs, the computer executes the instructions inside the greetUser procedure.

5. Defining vs. Calling

Term Meaning
Defining Creating the procedure
Calling Running or using the procedure

Example

PROCEDURE greetUser()
{
    DISPLAY("Welcome!")
}

greetUser()

The first part defines the procedure. The second part calls the procedure.

6. What Is a Function?

A function is similar to a procedure, but it usually returns a value.

A function performs a task and sends a result back to the part of the program that called it.

Example

PROCEDURE addNumbers(a, b)
{
    RETURN(a + b)
}

If the function is called like this:

sum ← addNumbers(4, 6)

The value of sum becomes:

10

7. Returning Values

A return value is the result sent back by a procedure or function.

Example

PROCEDURE squareNumber(num)
{
    RETURN(num * num)
}

Call:

answer ← squareNumber(5)

Result:

answer = 25

The function receives 5, squares it, and returns 25.

8. Procedures Without Return Values

Some procedures do not return a value. They simply perform an action.

Example

PROCEDURE printMenu()
{
    DISPLAY("1. Start Game")
    DISPLAY("2. View Scores")
    DISPLAY("3. Quit")
}

This procedure displays a menu but does not send back a value.

9. Procedures With Return Values

Some procedures calculate or produce a value and return it.

Example

PROCEDURE calculateArea(length, width)
{
    RETURN(length * width)
}

Call:

area ← calculateArea(8, 4)

Result:

area = 32

10. What Are Parameters?

Parameters are variables listed inside the parentheses of a procedure definition.

They allow a procedure to receive input.

Example

PROCEDURE greetStudent(name)
{
    DISPLAY("Hello, " + name)
}

Here, name is a parameter.

Call:

greetStudent("Alex")

Output:

Hello, Alex

11. Why Parameters Are Useful

Parameters make procedures flexible.

Without parameters, a procedure always does the same thing.

With parameters, a procedure can work with different values.

Example Without Parameters

PROCEDURE greetAlex()
{
    DISPLAY("Hello, Alex")
}

This only works for Alex.

Example With Parameters

PROCEDURE greetStudent(name)
{
    DISPLAY("Hello, " + name)
}

This works for many students:

greetStudent("Alex")
greetStudent("Maria")
greetStudent("Jordan")

12. Arguments vs. Parameters

Term Meaning
Parameter A variable in the procedure definition
Argument The actual value passed into the procedure call

Example

PROCEDURE displayScore(score)
{
    DISPLAY(score)
}

displayScore(95)

In this example:

13. Multiple Parameters

Procedures can have more than one parameter.

Example

PROCEDURE displayFullName(firstName, lastName)
{
    DISPLAY(firstName + " " + lastName)
}

Call:

displayFullName("Sam", "Rivera")

Output:

Sam Rivera

14. Order of Arguments Matters

When calling a procedure, arguments must be placed in the correct order.

Example

PROCEDURE subtract(a, b)
{
    RETURN(a - b)
}

Call:

result ← subtract(10, 4)

Result:

6

But this call:

result ← subtract(4, 10)

Result:

-6

The same numbers give different results because the order changed.

15. Modular Design

Modular design means breaking a large program into smaller, manageable parts.

Each part is responsible for a specific task.

These smaller parts are often procedures or functions.

Example

A game program might have separate procedures for:

16. Why Modular Design Matters

Modular design helps programmers:

17. Reusing Code

Procedures allow programmers to reuse code. Instead of writing the same instructions many times, write them once and call the procedure whenever needed.

Repeated Code Example

DISPLAY("Welcome!")
DISPLAY("Choose an option.")
DISPLAY("Welcome!")
DISPLAY("Choose an option.")

Better Version Using a Procedure

PROCEDURE showWelcome()
{
    DISPLAY("Welcome!")
    DISPLAY("Choose an option.")
}

showWelcome()
showWelcome()

This version is shorter, cleaner, and easier to update.

18. Abstraction

Procedures are a form of abstraction.

Abstraction means hiding unnecessary details so we can focus on the bigger idea.

When you call a procedure, you do not need to think about every line inside it. You only need to know what it does.

Example

calculateTotal()

The name tells us the purpose of the procedure, even if we do not see all the code inside it.

19. Procedural Abstraction

Procedural abstraction means using a procedure to hide the details of how a task is completed.

This makes programs easier to understand.

Example

PROCEDURE loginUser(username, password)
{
    // Code checks if the username and password are valid
}

A programmer can call:

loginUser("student1", "password123")

They do not need to focus on every detail of how the login system works.

20. AP CSP Pseudocode Example

PROCEDURE getAverage(num1, num2)
{
    RETURN((num1 + num2) / 2)
}

Call:

average ← getAverage(80, 90)

Result:

average = 85

21. Tracing a Procedure

Tracing means following the code step by step.

Example

PROCEDURE triple(x)
{
    RETURN(x * 3)
}

value ← triple(4)
DISPLAY(value)

Step-by-Step

  1. triple(4) is called.
  2. The argument 4 is assigned to the parameter x.
  3. The procedure calculates 4 * 3.
  4. The procedure returns 12.
  5. value becomes 12.
  6. The program displays 12.

22. Common Mistakes

Mistake Explanation
Defining but not calling The procedure exists but never runs
Forgetting parameters The procedure needs input but none is provided
Wrong argument order Values are passed in the wrong order
Forgetting RETURN A value is calculated but not sent back
Confusing DISPLAY and RETURN DISPLAY shows output; RETURN sends a value back

23. DISPLAY vs. RETURN

This is very important for AP CSP.

Command What It Does
DISPLAY Shows information to the user
RETURN Sends a value back to the program

Example Using DISPLAY

PROCEDURE showDouble(num)
{
    DISPLAY(num * 2)
}

This shows the result but does not return it.

Example Using RETURN

PROCEDURE getDouble(num)
{
    RETURN(num * 2)
}

This sends the result back so the program can store or use it.

24. Example: Procedure With Selection

Procedures can include selection, such as IF statements.

PROCEDURE checkPassing(grade)
{
    IF grade >= 70
    {
        RETURN("Passing")
    }
    ELSE
    {
        RETURN("Not Passing")
    }
}

Call:

status ← checkPassing(85)

Result:

status = "Passing"

25. Example: Procedure With Iteration

Procedures can also include loops.

PROCEDURE countToFive()
{
    count ← 1
    REPEAT 5 TIMES
    {
        DISPLAY(count)
        count ← count + 1
    }
}

This procedure displays:

1
2
3
4
5

26. Example: Procedure With a List

Procedures can use lists as parameters.

PROCEDURE displayList(items)
{
    FOR EACH item IN items
    {
        DISPLAY(item)
    }
}

Call:

displayList(["apple", "banana", "cherry"])

Output:

apple
banana
cherry

27. Benefits of Procedures and Functions

Procedures and functions help programmers write better code because they:

28. AP Exam Tip

On the AP CSP exam, pay close attention to:

29. Practice Example

PROCEDURE addTax(price)
{
    tax ← price * 0.08
    RETURN(price + tax)
}

total ← addTax(50)
DISPLAY(total)

Trace

  1. addTax(50) is called.
  2. price becomes 50.
  3. tax becomes 50 * 0.08, which is 4.
  4. The procedure returns 50 + 4.
  5. total becomes 54.
  6. The program displays 54.

30. Summary

Procedures and functions allow programmers to organize code into reusable sections. A procedure is defined with a name and instructions, and it runs when it is called. Parameters allow procedures to accept input, and return values allow functions to send results back to the program.

Using procedures supports modular design, reduces repeated code, and makes programs easier to read, test, and debug.