ruby exponent
def power(base, exponent)
result = 1
while exponent > 0
result *= base
exponent -= 1
end
return result
end
puts power(2, 3) # Output: 8
Explanation:
- def power(base, exponent)
defines a method named power
that takes two parameters: base
and exponent
.
- result = 1
initializes a variable result
to store the computed value, starting with 1.
- while exponent > 0
creates a loop that continues as long as the exponent
is greater than 0.
- result *= base
multiplies the result
by the base
value in each iteration of the loop.
- exponent -= 1
decrements the exponent
value by 1 in each iteration.
- return result
specifies the value of result
to be returned once the loop finishes.
- puts power(2, 3)
calls the power
method with arguments 2 and 3 and prints the result, which in this case is 8.