Resources | Subject Notes | Computer Science
In structured programming, procedures (also known as subroutines or functions) are fundamental building blocks that allow you to break down a large program into smaller, more manageable and reusable sections. They promote modularity, making code easier to understand, debug, and maintain.
A procedure is a sequence of instructions that performs a specific task. It can accept input values (parameters), process those values, and optionally return a result. Procedures help avoid code repetition and improve program organization.
To define a procedure, you specify its name, the parameters it accepts (if any), and the block of code that makes up the procedure's body. The syntax for defining a procedure varies depending on the programming language, but the general concept remains the same.
Consider the following pseudocode example:
Line | Code | Description |
---|---|---|
1 | procedure CalculateArea(length, width) | Defines a procedure named 'CalculateArea' that takes two parameters: 'length' and 'width'. |
2 | area = length * width | Calculates the area by multiplying length and width. |
3 | output area | Displays the calculated area. |
4 | end procedure | Marks the end of the procedure definition. |
To execute a procedure, you 'call' it. This involves using the procedure's name followed by parentheses containing any required arguments (values to be passed to the procedure's parameters).
Using the same pseudocode example:
Line | Code | Description |
---|---|---|
1 | CalculateArea(5, 10) | Calls the 'CalculateArea' procedure with arguments 5 and 10. The procedure will calculate the area of a rectangle with length 5 and width 10. |
Parameters: Variables declared in the procedure definition that act as placeholders for input values.
Arguments: The actual values passed to the procedure when it is called. Arguments are assigned to the corresponding parameters.
Let's consider a procedure that calculates the volume of a cylinder:
Line | Code | Description |
---|---|---|
1 | procedure CalculateCylinderVolume(radius, height) | Defines a procedure to calculate the volume of a cylinder. |
2 | volume = $\pi \times radius^2 \times height$ | Calculates the volume using the formula. |
3 | output volume | Displays the calculated volume. |
4 | end procedure | Marks the end of the procedure definition. |
To use this procedure:
Line | Code | Description |
---|---|---|
1 | CalculateCylinderVolume(2, 10) | Calls the procedure with a radius of 2 and a height of 10. |
This procedure demonstrates how parameters and arguments are used to pass data to the procedure and calculate the volume based on that data.