Calculate the Power of a Number
Let's start by defining the function calculatePower
. This function will take two parameters: base
and exponent
.
function calculatePower(base, exponent) { // Function body will go here }
To compute the power of a number, we use the concept of repeated multiplication. For example, to calculate base
raised to the power of exponent
, we multiply base
by itself exponent
times.
We start by initializing a variable named result
to 1
. This variable will store the final computed value after raising the base
to the power of exponent
.
We then use a for loop to iterate exponent
times. In each iteration of the loop, we multiply the current value of result
by base
. This operation effectively accumulates the multiplication base * base * ...
for exponent
times.
By the end of the loop, result
will hold the value of base
raised to the power of exponent
.
function calculatePower(base, exponent) { // Calculate the power let result = 1; for (let i = 0; i < exponent; i++) { result *= base; } // Return the calculated power return result; }