Define and use a function

11.3 Structured Programming – Define and Use a Function

📘 What is a Function?

A function is a named block of code that performs a specific task. It can take inputs (parameters), process them, and return a result. Using functions makes programs easier to read, test, and reuse.

🔧 How to Define a Function (Pseudocode)

  1. Choose a meaningful name that describes the action.
  2. List any parameters inside parentheses, separated by commas.
  3. Write the steps the function should perform.
  4. Optionally, use return to send a value back to the caller.

🧮 Example: Calculating the Area of a Rectangle

Step Pseudocode
1. Define function FUNCTION AreaRectangle(length, width)
RETURN length × width
END FUNCTION
2. Call function $area = AreaRectangle(5, 3)$
OUTPUT $area$
3. Result $area = 15$ (square units)

?? Benefits of Using Functions

  • 🔹 Modularity: Break a large program into manageable pieces.
  • 🔹 Reusability: Write once, use many times.
  • 🔹 Abstraction: Hide complex details behind a simple name.
  • 🔹 Easier Debugging: Test each function independently.

⚠️ Common Pitfalls to Avoid

  • 🚫 Forgetting to return a value when needed.
  • 🚫 Using the same variable name inside and outside the function causing confusion.
  • 🚫 Not defining parameters correctly (missing commas or wrong order).
  • 🚫 Over‑loading a function with too many responsibilities.

💡 Quick Checkpoint

Write a function IsEven(n) that returns True if integer n is even, otherwise False. Test it with the values 4, 7, and 0.

Revision

Log in to practice.

1 views 0 suggestions