Published by Patrick Mutisya · 14 days ago
Explain where in the construction of an algorithm it would be appropriate to use a procedure.
Procedures (also called sub‑routines or functions) are blocks of code that perform a specific task and can be called from multiple points in an algorithm. They help to:
Identify repeated or complex operations that can be isolated. For example, “convert temperature”, “search a list”, or “calculate factorial”.
Write high‑level steps. When a step represents a self‑contained task, replace it with a procedure call placeholder.
Example:
Read input values
CALL sortArray(values)
Display sorted values
Define the procedure’s purpose, inputs, outputs, and internal steps. This can be captured in a separate pseudocode block.
PROCEDURE sortArray(arr)
// implementation of sorting algorithm
END PROCEDURE
Insert the procedure call at the appropriate point in the main flow, ensuring that data dependencies are satisfied.
Test the procedure independently (unit testing) before testing the full algorithm (integration testing).
| Situation | Reason for Procedure | Example |
|---|---|---|
| Repeated calculations | Avoids rewriting the same formula many times. | Calculating the area of different shapes. |
| Complex decision logic | Encapsulates nested conditionals, making the main flow clearer. | Validating user input against multiple criteria. |
| Data manipulation on collections | Provides a single point to change the algorithm (e.g., switch sorting method). | Sorting, searching, or merging lists. |
| Input/Output handling | Separates I/O from core processing, aiding portability. | Reading a file, formatting output. |
Consider an algorithm that processes student marks and assigns grades. The grading logic is used several times, so it is extracted as a procedure.
MAIN
READ numberOfStudents
FOR i FROM 1 TO numberOfStudents DO
READ studentName, mark
grade ← CALL determineGrade(mark)
OUTPUT studentName, mark, grade
END FOR
END MAIN
PROCEDURE determineGrade(m)
IF m ≥ 80 THEN RETURN 'A'
ELSE IF m ≥ 70 THEN RETURN 'B'
ELSE IF m ≥ 60 THEN RETURN 'C'
ELSE IF m ≥ 50 THEN RETURN 'D'
ELSE RETURN 'F'
END IF
END PROCEDURE
In this example, the procedure determineGrade is introduced after the repeated grading logic is identified (step 1) and is then called from the main loop (step 4).
The decision process can be expressed as a piecewise function:
\$\$
\text{grade}(m) =
\begin{cases}
A & \text{if } m \ge 80 \\
B & \text{if } 70 \le m < 80 \\
C & \text{if } 60 \le m < 70 \\
D & \text{if } 50 \le m < 60 \\
F & \text{if } m < 50
\end{cases}
\$\$
determineGrade procedure, with the procedure’s internal decision block.