Subroutines (1)
Subroutines (1)
Chapter 8
Subroutines
• A subroutine is a self-contained piece of code that has an identifier(name) and using that identifier(name) it can be called from
• When a problem is decomposed into sub-system, each of the sub-system, can be written as a subroutine.
• Procedure and function can both receive one or more values as parameters.
• These are values that are sent to the subroutine from the calling part of the program.
Key Words Key Words Key Words Key Words
Subroutine: Procedure: Function: Parameter:
• Procedure: A procedure runs the code inside it and does not return a value to the program that called it. It can be
called from other parts of the program using their name.
PROCEDURE calculate_area(length:
PROCEDURE Identifier() // procedure INTEGER, width: INTEGER)
header area ← length * width
OUTPUT "The area is “, area
codes to run inside the ENDPROCEDURE
function // procedure body
# Calling the procedure in program:
ENDPROCEDURE calculate_area(5, 3)
calculate_area(6, 3)
# Calling the procedure in program
• Function: A function returns a value to the program that called it. This can be done by using the RETURN keyword. Once
a value is returned, the function stops running.
• Functions can be called from other parts of the program using their name, and their return value can be stored in a
variable.
• Consider an example of a system that stores the height and
width of two rectangles and calculates their area. The system
• The pseudocode definition of a function is:
also outputs the area with a suitable message.
• Scope of a variable is the areas within a program where the variable can be accessed.
Example
Output
Main program
Procedure