CS221 Module5
CS221 Module5
SUBROUTINES
These subroutines are designed to be called or invoked from other parts of the program,
allowing for modularization and code reuse.
3. Readability: By organizing code into subroutines, the main program becomes more
readable and easier to understand. Each subroutine typically has a well-defined
purpose, making it clear what it does.
In this example, the ‘greet’ subroutine takes a ‘name’ parameter and prints a greeting.
The subroutine can be called multiple times with different names, demonstrating the
reusability and parameterization aspects of subroutines.
Example-2 where a subroutine is used to calculate the area of a rectangle. The subroutine
will take the length and width of the rectangle as parameters and return the calculated
area.
In this example:
1. The calculate_rectangle_area subroutine takes two parameters, length and
width.
2. Inside the subroutine, the area of the rectangle is calculated using the formula area
= length * width.
3. The calculated area is then returned from the subroutine.
4. Outside the subroutine, the program provides values for the length and width of a
rectangle.
5. The subroutine is called with these values, and the result (area_of_rectangle) is
printed.
This example illustrates how a subroutine can encapsulate a specific calculation, making
the code more modular and reusable. You can easily reuse the
calculate_rectangle_area subroutine with different length and width values in various
parts of your program.
Expected Output
The area of the rectangle is: 40 square units.
Here's the equivalent C++ program based on the Python example-2 for calculating the
area of a rectangle:
In this C++ program:
1. I declared a function prototype for the calculate_rectangle_area subroutine.
2. The main function provides values for the length and width of a rectangle.
3. The calculate_rectangle_area subroutine is called with these values, and the
result is stored in the area_of_rectangle variable.
4. The result is then displayed using std::cout.
Types of Subroutines
1. Function Subroutines
2. Procedure Subroutines
3. Recursive Subroutines
4. Interrupt Service Subroutines (ISR)
5. Event-Driven Subroutines
6. User-Defined Functions
7. Library Subroutines
8. Inline Subroutines
Different programming languages may use different terms or have specific implementations for
these types of subroutines, but the general concepts are applicable across many languages.