Let the loop run downwards. Then the
exponent
value can be assigned to the loop variable initially. Because you have to initialise the result too and will use
exponent
, this must be done after initialising the loop variable. Fortunately, C/C++
for
loops allow multiple statements in the init expression.
Putting it all together and initialising the result with one to get the correct result when
exponent
is zero (requires one more iteration than in your code):
for (int i = exponent - 1, exponent = 1; i >= 0; i--)
{
exponent *= base;
}