Subprograms are reusable blocks of code that perform specific tasks. They are also known as functions or procedures. Subprograms help us create modular code, which is easier to read, understand, and maintain.
1. Procedures: - Perform a set of actions without returning a value. - Example: Printing a welcome message to the user.
2. Functions: - Perform a set of actions and return a value. - Example: Calculating the square of a number.
# This is a function that calculates the area of a rectangle.
function calculateArea(length, width):
area = length * width
return area
# This is the main program that calls the calculateArea function.
main():
length = 10
width = 5
area = calculateArea(length, width)
print("The area of the rectangle is:", area)
Explanation:
calculateArea()
function takes length
and width
as inputs and calculates the area
before returning it.main()
function calls calculateArea()
with specific values and prints the result.1. Global Variables: - Declared outside any subprogram. - Accessible from anywhere in the program.
2. Local Variables: - Declared inside a subprogram. - Only accessible within the subprogram they are declared in.
Example:
global_var = 10
function myFunction():
local_var = 5
print("Global variable:", global_var)
print("Local variable:", local_var)
main():
print("Global variable:", global_var)
# Error: local_var is not accessible here
# print("Local variable:", local_var)
Explanation:
global_var
is accessible both in the myFunction()
and main()
functions.local_var
is only accessible inside myFunction()
.By following these steps, you can create modular programs that are well-organized, efficient, and easy to maintain.