Resources | Subject Notes | Computer Science
A procedure is a sequence of instructions that perform a specific task. It's a set of steps designed to achieve a particular outcome. In programming, procedures (also known as subroutines or methods in some languages) are fundamental for breaking down complex tasks into smaller, manageable units. This improves code organization, readability, and reusability.
Here's a simple example of a procedure in pseudocode:
A function is a type of procedure that returns a value. Functions are essential for modular programming, allowing you to encapsulate a block of code that performs a specific calculation or operation and then return the result of that operation. Functions enhance code reusability and make programs easier to understand and debug.
Functions can accept parameters, which are inputs that the function uses to perform its task. Parameters are listed within the function definition, and the values passed to the function when it's called are known as arguments.
Parameters are variables that act as placeholders for values that will be used within the function. They allow functions to be more flexible and adaptable. There are different types of parameters:
Consider a function that calculates the area of a rectangle. It needs the length and width as input.
Parameter Name | Purpose |
---|---|
length | The length of the rectangle. |
width | The width of the rectangle. |
Here's a pseudocode example of a function to calculate the area:
To use a function, you need to call it. When you call a function, you pass the required arguments (values) to the function's parameters.
Example:
Here's a simple example of a function in Python that takes a parameter and returns a value:
def greet(name): """This function greets the person passed in as a parameter.""" message = "Hello, " + name + "!" return message person_name = "Alice" greeting = greet(person_name) print(greeting) # Output: Hello, Alice!