Write your first function: raise a number to a power with a loop.
What to build
A program with a power function.
Requirements
- Write a function
power(int $base, int $exp): intthat multiplies the base by itself exp times (do not use the ** operator). - Read base and exponent and print the result.
Input
One line: base and exponent.
Output
One integer.
Constraints
0 ≤ exponent ≤ 30; the result is at most 1000000000.
Example
Input:
2 10
Output:
1024
Why it works
The function hides the loop behind a name, and a result that starts at 1 handles exponent 0 correctly.
Examples
Example 1 · Input
2 10
Expected output
1024
Example 2 · Input
5 0
Expected output
1
Hints
Hint 1
Write function power(int $base, int $exp): int with a loop that multiplies.
Hint 2
Start the result at 1, so that exponent 0 gives 1.
Solution
Show one correct solution (try it yourself first)
<?php
function power(int $base, int $exp): int
{
$result = 1;
for ($i = 0; $i < $exp; $i++) {
$result *= $base;
}
return $result;
}
fscanf(STDIN, "%d %d", $b, $e);
echo power($b, $e), "\n";