basics · beginner · ~15 min

Integer power (iterative)

Loop accumulation patterns.

Challenge

Raise an integer to a non-negative power using a loop.

Task

Implement long ipow(int base, int exp) that returns base raised to the power exp, computed by iterative multiplication. By definition any base to the power 0 is 1.

Input

An int base and a non-negative int exp.

Output

Returns base^exp as a long.

Example

ipow(2, 10)   ->   1024
ipow(3, 5)    ->   243
ipow(7, 0)    ->   1
ipow(10, 6)   ->   1000000

Edge cases

  • exp == 0 returns 1 for any base.

Input format

An int base and a non-negative int exp.

Output format

base raised to exp, as a long.

Constraints

exp is non-negative. base^0 == 1.

Starter code

long ipow(int base, int exp) { /* TODO */ return 0; }

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.