Parameters CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumWrite a function called power(base, exponent) that returns base raised to the exponent using a loop. Trace power(2, 4).
Solution
- 1 Step 1: FUNCTION power(base, exponent): SET result = 1. FOR i = 1 TO exponent: result = result * base. RETURN result.
- 2 Step 2: power(2, 4): result = 1โ2โ4โ8โ16. Returns 16.
Answer
power(2, 4) = 16. The function multiplies base by itself exponent times.
Parameters allow this single function to compute any power โ power(3, 2) = 9, power(10, 3) = 1000. Without parameters, you would need separate functions for each calculation.
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 4 hardExplain the difference between passing by value and passing by reference. If FUNCTION double(x): x =