Chapter 5

Functions and Procedures

Functions and procedures are named blocks of code; a function returns a value while a procedure does not, and both can take parameters.

Large programs are split into smaller named blocks so code can be reused and understood. Two such blocks are the function and the procedure.

The key difference

A function does a task and returns a value back to the part of the program that called it. A procedure does a task but does not return a value; it simply performs an action, such as printing a message.

Key idea

Function → returns a value. Procedure → returns no value. Both can take parameters, which are inputs passed in when the block is called.

Parameters

A parameter is a value passed into a function or procedure so it can work with different inputs. Both functions and procedures may have parameters, and a block can have none, one, or several. Passing different values as parameters lets the same block give different results, which is why parameters make code flexible and reusable. When you use a function or procedure in your program, you call it by its name and give it the values its parameters need.

Example

A function addNumbers(a, b) takes two parameters and returns their sum: return a + b. Calling addNumbers(3, 4) gives back 7, which can be stored or displayed. A procedure greet(name) takes one parameter and just prints Hello name without returning anything.

Remember

  • A function returns a value; a procedure does not.
  • Both can take parameters as input.
  • Splitting code into functions and procedures avoids repetition.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor