Define and use a procedure

11.3 Structured Programming: Define and Use a Procedure 📚

What is a Procedure? 🤔

A procedure is like a recipe in a cookbook. It’s a named block of code that performs a specific task. Once you’ve written the recipe, you can use it any time you need that task done, without having to rewrite the steps.

Syntax of a Procedure 🛠️

In pseudocode, a procedure is defined with the keyword PROCEDURE followed by its name and optional parameters.

  1. PROCEDURE name(param1, param2, …)
  2. Procedure body (indented)
  3. END PROCEDURE

Example:

PROCEDURE greet(name)
    PRINT "Hello, " + name + "!"
END PROCEDURE

Calling a Procedure 🚀

To use a procedure, simply write its name and supply any required arguments.

  1. greet("Alice")
  2. greet("Bob")

Parameters and Return Values 🔁

Parameters act like ingredients: they give the procedure the data it needs. A procedure can also return a value, similar to a finished dish.

  • Input parameters – data passed into the procedure.
  • Output parameters – data returned out of the procedure.
  • Return type is optional in many languages; if omitted, the procedure returns void.

Example with return value:

PROCEDURE add(a, b)
    RETURN a + b
END PROCEDURE

Scope and Local Variables 🌐

Variables declared inside a procedure are local – they exist only while the procedure runs. They cannot be accessed outside the procedure.

  1. DECLARE localVar
  2. Use localVar inside the procedure.
  3. After the procedure ends, localVar is destroyed.

Example: Calculating Factorial (Recursive) 🔢

Factorial of a number n is defined as:

$$ n! = n \times (n-1)! $$

Here’s a recursive procedure:

PROCEDURE factorial(n)
    IF n = 0 THEN
        RETURN 1
    ELSE
        RETURN n * factorial(n - 1)
    END IF
END PROCEDURE

Exam Tips for Procedures 📌

  • Always include the PROCEDURE keyword and the matching END PROCEDURE.
  • Remember that parameters are passed by value unless specified otherwise.
  • Check that the procedure’s return type matches the expected output.
  • Use clear, descriptive names for procedures and parameters.
  • When asked to write a procedure, start with the signature, then the body, and finish with the return statement.

Quick Quiz ❓

  1. What keyword marks the start of a procedure?
  2. Can a procedure access a variable declared outside its body?
  3. Write a simple procedure that prints “Goodbye!”.

Summary Table of Procedure Components 📊

Component Description Example
Signature Name + parameters PROCEDURE greet(name)
Body Code that performs the task PRINT "Hello, " + name + "!"
Return Optional value sent back to caller RETURN a + b
End Marks the end of the procedure END PROCEDURE

Revision

Log in to practice.

2 views 0 suggestions