0% found this document useful (0 votes)
17 views

CS221 Module5

The document discusses subroutines, which are reusable blocks of code that perform specific tasks. It provides examples of subroutines in Python and C++, and explains that subroutines promote modularity, reusability, readability, and easier debugging. The document also compares different types of subroutines such as functions, procedures, recursive subroutines, and interrupt service routines.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

CS221 Module5

The document discusses subroutines, which are reusable blocks of code that perform specific tasks. It provides examples of subroutines in Python and C++, and explains that subroutines promote modularity, reusability, readability, and easier debugging. The document also compares different types of subroutines such as functions, procedures, recursive subroutines, and interrupt service routines.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNDERSTANDING SUBROUTINES AND KEY PROGRAMMING CONCEPTS

SUBROUTINES

Definition and Purpose of Subroutines

 Subroutines, also known as functions or procedures in various programming


languages, are reusable and self-contained blocks of code that perform a specific task
or set of tasks within a program.

 These subroutines are designed to be called or invoked from other parts of the program,
allowing for modularization and code reuse.

 The primary purposes of subroutines include:

1. Modularity: Subroutines promote modularity by breaking down a large program into


smaller, more manageable pieces. Each subroutine can handle a specific aspect of
the program's functionality.

2. Reusability: Since subroutines encapsulate specific tasks, they can be reused in


different parts of the program or even in other programs. This reduces redundancy
and makes the codebase more maintainable.

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.

4. Debugging: Subroutines facilitate debugging by isolating specific functionalities.


When an issue arises, developers can focus on the relevant subroutine, making it
easier to identify and fix problems.

5. Parameterization: Subroutines often accept parameters, allowing them to work with


different data or perform variations of a task. This enhances flexibility and adaptability
in the code.

 Example-1 in Python to illustrate a subroutine:


Expected Output:
Hello, Alice!
Hello, Bob!

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.

 The equivalent C++ program based on the Python example-1:

In this C++ program:


1. I declared a function prototype for the greet subroutine at the beginning to inform
the compiler about the function's signature before it's defined.
2. The main function is the entry point of the program, and it calls the greet
subroutine with different names.
3. The greet subroutine takes a const std::string& name parameter and prints a
greeting using std::cout.

 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.

COMPARISON BETWEEN FUNCTION SUBROUTINES AND PROCEDURE SUBROUTINES


Function Subroutines Procedure Subroutines
Returns a value to the calling code. Performs a set of instructions without
returning a value.
Purpose
Typically used for calculations or Primarily focuses on executing a
operations that yield a result. sequence of steps.
Used when the main program needs Used when the main program needs to
a result or value computed by the execute a series of tasks or steps.
subroutine.
Usage Well-suited for mathematical Suitable for operations where the focus
calculations, data transformations, or is on performing actions rather than
any task where the result is important computing a result.
to the calling code.
In many programming languages, you A procedure to print a message on the
might define a function to calculate screen or update a database record
Example the square root of a number. without returning a value.
def calculate_square_root(number): def print_message(message):
return math.sqrt(number) print(message)
Comparison Summary
Function Subroutines return a value to Procedure Subroutines do not return a
Return Value
the calling code. value; they focus on performing tasks
Function Subroutines are suitable for Procedure Subroutines are suitable for
Purpose tasks where a result or value is sequences of actions or tasks without
needed in the calling code. an emphasis on returning a value.
Function Subroutines are used for Procedure Subroutines are used for
Usage calculations, data transformations, or executing a series of steps or tasks.
any task where the result is important.
Function Subroutine example Procedure Subroutine example
Example involves calculating the square root. involves printing a message without
returning a value.
Both types of subroutines play crucial roles in structuring and organizing code based on the
specific needs of a program.

COMPARISON BETWEEN RECURSIVE SUBROUTINES AND INTERRUPT SERVICE


SUBROUTINES
Recursive Subroutines Interrupt Service Subroutines
Purpose Calls itself to solve a smaller Handles interrupts, responding to
instance of the same problem. events that occur asynchronously.
Usage Useful for solving problems that Used in real-time systems or
can be broken down into smaller, situations where events may
similar sub-problems. occur unpredictably.
Example Recursive functions are An ISR might handle input from a
commonly used in algorithms like keyboard or respond to a
those for calculating factorials or hardware interrupt.
traversing tree structures.
Characteristics Recursive subroutines involve ISRs are specialized subroutines
breaking down a larger problem that are triggered by hardware or
into smaller, identical sub- software interrupts. They are
problems until a base case is designed to handle events that
reached. The results of the occur asynchronously to the
smaller sub-problems are then normal flow of the program. ISRs
combined to solve the original are critical in real-time systems
problem. where timely responses to
external events are crucial.
Comparison Summary
Purpose Solve a larger problem by Handle asynchronous events,
breaking it down into smaller, such as interrupts, in real-time
identical sub-problems. systems.
Usage Suitable for problems that exhibit Used in scenarios where events
a divide-and-conquer structure, can occur at unpredictable times,
where solving a larger problem requiring immediate and
involves solving smaller deterministic responses.
instances of the same problem.
Example Commonly used in algorithms Handles hardware interrupts (e.g.,
like calculating factorials or keyboard input) or software
traversing tree structures. interrupts in real-time systems.
Both recursive subroutines and ISRs play crucial roles in different aspects of
programming, addressing distinct challenges related to problem-solving and real-time
system responsiveness.
COMPARISON BETWEEN EVENT-DRIVEN SUBROUTINES AND USER-DEFINED
FUNCTIONS

Event-Driven Subroutines User-Defined Functions


Purpose Responds to specific events or Created by the programmer to
triggers. encapsulate specific functionality.
Usage Common in graphical user Provides a way to organize code
interfaces (GUIs) or applications and make it more modular and
with event-driven architectures. readable.
Example Handling a button click or a A user-defined function to validate
mouse hover event in a graphical user input or format data.
application.
Characteristics Event-driven subroutines are User-defined functions are
designed to respond to external functions created by the
events, such as user actions or programmer to perform a specific
system notifications. They wait task. They are typically used to
for events to occur and execute encapsulate functionality,
specific actions in response to promote code reusability, and
those events. enhance the organization and
readability of the code.
Comparison Summary
Purpose Event-Driven Subroutines: Created by the programmer to
Respond to specific events or encapsulate specific functionality
triggers, often related to user for code organization and
interactions in GUIs. reusability.
Usage Commonly used in applications Used to encapsulate and reuse
where actions are triggered by specific functionality within a
external events, such as user program, improving code
input or system notifications. modularity and readability.
Example Handling a button click or a Validating user input or formatting
mouse hover event in a graphical data in a customized manner.
application.
Both event-driven subroutines and user-defined functions contribute to the structure and
functionality of a program, but they serve different purposes and are applied in different
contexts within software development.

COMPARISON BETWEEN LIBRARY SUBROUTINES AND INLINE SUBROUTINES

Library Subroutines Inline Subroutines


Purpose Part of a library of pre-written Directly inserted into the code at
functions that can be used by the point where they are called.
multiple programs.
Usage Saves time and effort by reusing Reduces the overhead associated
common functionality. with subroutine calls.
Example Functions provided by a math Inlining a short piece of code
library for trigonometric instead of creating a separate
calculations. function for it.
Characteristics Library subroutines are part of a Inline subroutines involve directly
collection of functions bundled inserting the code at the location
together in a library. These where they are called, as opposed
functions are designed to to making a separate function call.
perform common tasks, and they This can reduce the overhead
can be reused across multiple associated with function calls but
programs without rewriting the is typically suitable for short and
same code. They promote code simple pieces of code.
reuse and modularity.
Comparison Summary
Purpose Provide a collection of reusable Reduce the overhead associated
functions for common tasks. with function calls for short and
simple code snippets.
Usage Used to save time and effort by Used to optimize performance by
reusing common functionality avoiding the overhead of function
across multiple programs. calls for short code snippets.
Example Functions provided by a math Inlining a short piece of code
library for trigonometric instead of creating a separate
calculations. function for it.
Both library subroutines and inline subroutines serve different purposes. Library
subroutines focus on providing a reusable collection of functions, while inline
subroutines are used to optimize performance by avoiding the overhead associated with
function calls for short code snippets.

You might also like