Parameters CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
hardExplain the difference between passing by value and passing by reference. If FUNCTION double(x): x = x * 2 is called with SET a = 5. double(a), what is the value of a after the call in each case?
Solution
- 1 Step 1: Pass by value: a copy of a is passed. The function modifies the copy. a remains 5 after the call.
- 2 Step 2: Pass by reference: the actual variable a is passed. The function modifies a directly. a becomes 10 after the call.
- 3 Step 3: Most languages use pass by value for simple types (integers, strings). Pass by reference is used for large data structures to avoid copying overhead.
Answer
By value: a = 5 (unchanged). By reference: a = 10 (modified).
Understanding parameter passing mechanisms is essential for predicting function behaviour. Pass by value is safer (no side effects) while pass by reference is more efficient for large data.
About Parameters
Named values declared in a function definition that act as placeholders for the actual data (arguments) passed in when the function is called. Parameters allow the same function to operate on different data each time it is invoked.
Learn more about Parameters โMore Parameters Examples
Example 1 easy
What is the output of the following? FUNCTION greet(name): OUTPUT 'Hello, ' + name. greet('Alice').
Example 2 mediumFUNCTION calculateArea(length, width): RETURN length * width. What is calculateArea(5, 3)? What happ
Example 3 mediumWrite a function called power(base, exponent) that returns base raised to the exponent using a loop.