Use the terminology associated with procedures and functions
11.3 Structured Programming 📚
Structured programming is all about breaking down a problem into smaller, manageable pieces called procedures and functions. Think of them as mini‑recipes that you can reuse throughout your code.
Terminology Overview
- Procedure – A block of code that performs a task but does not return a value. It’s like a cooking step that doesn’t give you a final dish.
- Function – Similar to a procedure but it returns a value. Think of it as a blender that gives you a smoothie.
- Parameter – A variable listed in the procedure/function definition. It’s a placeholder for data you’ll supply later.
- Argument – The actual value you pass to a parameter when you call the procedure/function.
- Return Value – The result produced by a function and sent back to the caller.
- Scope – The region of the program where a variable is visible. Local scope is inside a procedure/function; global scope is outside.
Procedures vs Functions
Both are called subroutines, but the key difference is the return value:
| Type | Purpose | Example |
|---|---|---|
| Procedure | Performs an action, no value returned. | void printWelcome() |
| Function | Performs an action and returns a value. | int add(int a, int b) |
Parameters & Arguments
When you define a procedure/function you specify parameters:
int multiply(int x, int y) { return x * y; }
When you call it you supply arguments:
int result = multiply(4, 5); // 4 and 5 are arguments
Return Values
A function uses the return keyword to give back a value. The type of the return value must match the function’s declared return type.
double average(int total, int count) {
return (double)total / count;
}
If you forget return, the function may produce an error or an undefined value.
Scope & Lifetime
Variables declared inside a procedure/function are local and disappear once the block ends. Variables declared outside are global and exist throughout the program.
int globalScore = 0; // global
void updateScore(int points) {
int localScore = points; // local
globalScore += localScore;
}
Recursion (Optional)
A function that calls itself. Use it carefully to avoid infinite loops.
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Exam Tips 📝
- Identify whether the question asks for a procedure (no return) or a function (return value).
- Use clear parameter names that describe the data (e.g.,
numStudents,averageScore). - Show the
returnstatement explicitly if a value is required. - Remember to declare the correct return type (int, double, void, etc.).
- Explain the difference between parameters and arguments in your answer.
- When using recursion, state the base case and the recursive case.
Quick Quiz 🚀
Which of the following is a function?
void displayMessage()int calculateSum(int a, int b)string getName()
Answer: The ones that return a value (int, string) are functions; the one with void is a procedure.
Revision
Log in to practice.