Parameters CS Thinking Example 3

Follow the full solution, then compare it with the other examples linked below.

Example 3

medium
Write a function called power(base, exponent) that returns base raised to the exponent using a loop. Trace power(2, 4).

Solution

  1. 1
    Step 1: FUNCTION power(base, exponent): SET result = 1. FOR i = 1 TO exponent: result = result * base. RETURN result.
  2. 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