Parameters CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumFUNCTION calculateArea(length, width): RETURN length * width. What is calculateArea(5, 3)? What happens if you call calculateArea(5) with only one argument?
Solution
- 1 Step 1: calculateArea(5, 3) assigns length = 5, width = 3. Returns 5 * 3 = 15.
- 2 Step 2: calculateArea(5) provides only one argument but the function expects two parameters.
- 3 Step 3: This causes an error โ the function cannot execute because width has no value. The number of arguments must match the number of parameters.
Answer
calculateArea(5, 3) = 15. calculateArea(5) causes an error due to a missing argument.
Functions require the correct number of arguments to match their parameters. Mismatched argument counts are a common source of errors in programming.
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 3 mediumWrite a function called power(base, exponent) that returns base raised to the exponent using a loop.
Example 4 hardExplain the difference between passing by value and passing by reference. If FUNCTION double(x): x =