Define and use procedures and functions with or without parameters

Resources | Subject Notes | Computer Science

Programming Concepts: Procedures and Functions

Programming Concepts: Procedures and Functions

Introduction

In computer programming, procedures and functions are fundamental building blocks that allow us to organize code, make it reusable, and improve readability. They help break down complex tasks into smaller, manageable units.

Procedures

A procedure is a sequence of instructions that performs a specific task. It's a self-contained block of code that can be executed when needed. Procedures do not necessarily return a value.

Example (Python):


def greet(name):
    print("Hello, " + name + "!")

greet("Alice")

In this example, `greet` is a procedure that takes a name as input and prints a greeting. It doesn't return any value.

Functions

A function is a type of procedure that does return a value. Functions can accept input values (parameters) and produce an output. They are essential for modular programming.

Example (Python):


def add(x, y):
    return x + y

result = add(5, 3)
print(result)

Here, `add` is a function that takes two parameters, `x` and `y`, adds them together, and returns the result. The returned value is then stored in the variable `result` and printed.

Parameters

Parameters are variables that are used to pass data into a function or procedure. They act as placeholders for values that will be used within the code.

There are different types of parameters:

  • Required Parameters: These are parameters that must be provided when the function is called.
  • Optional Parameters: These are parameters that have a default value if no value is provided when the function is called.

Types of Functions

Functions can be categorized based on the number of parameters they accept:

Function Type Description Example (Python)
No Parameters The function does not require any input values.

def say_hello():
    print("Hello everyone!")

say_hello()
One Parameter The function requires one input value.

def square(number):
    return number * number

result = square(5)
print(result)
Two or More Parameters The function requires multiple input values.

def calculate_area(length, width):
    return length * width

area = calculate_area(10, 5)
print(area)

Using Procedures and Functions

By using procedures and functions, you can:

  • Make your code more organized and easier to understand.
  • Avoid repeating the same code multiple times.
  • Make your code more reusable.
  • Simplify complex tasks.

Exercise

  1. Write a function that takes the radius of a circle as a parameter and returns its area.
  2. Write a procedure that takes a list of numbers as input and prints the sum of the numbers.