Define and use procedures and functions with or without parameters

Programming Concepts: Procedures & Functions

🛠️ What is a Procedure?

A procedure is a block of code that performs a specific task but does not return a value. Think of it as a recipe that tells the computer how to bake a cake, but it doesn’t give you the cake’s weight or price. In programming, we call it a subroutine or method.

📐 What is a Function?

A function is similar to a procedure but it returns a value after execution. Imagine a vending machine: you insert coins (input) and it gives you a snack (output). In code, the function takes arguments, performs calculations, and returns a result. Example:

function add(a, b) {
    return a + b;
}

Here, add returns the sum of a and b.

🔧 Defining Procedures & Functions

  • Choose a clear, descriptive name.
  • Decide if it needs to return a value (function) or not (procedure).
  • List any parameters it will accept.
  • Write the body of code that performs the task.
  • Use return only in functions.

🚀 Using Procedures & Functions

  1. Call the procedure/function by its name.
  2. Pass the required arguments in the correct order.
  3. For functions, store the returned value if needed.
  4. Repeat as necessary.

⚙️ Parameters & Arguments

- Parameters are variables listed in the function/procedure definition. - Arguments are the actual values you pass when calling it.

Definition Example
Procedure with no parameters
procedure greet() {
    print("Hello, world!");
}
Function with parameters
function multiply(x, y) {
    return x * y;
}
Calling a function
let result = multiply(4, 5);  // result = 20

💡 Exam Tips

Remember:

  • Identify whether the task requires a value to be returned.
  • Use clear, descriptive names for procedures/functions.
  • Check parameter order and type when calling.
  • For functions, always include a return statement.
  • Practice writing both simple and nested procedures/functions.

Good luck! 🚀

Revision

Log in to practice.

0 views 0 suggestions