Answer to Question 09F-2
We want to initialize p = 1 and to multiply p by x a total of n times.
From the preceding problem, we know how to perform something n times. Here is a skeleton that
repeats STEP n times.
int i = 1;
while(i <= n)
{
STEP
i++;
}
Now lets add initialization of p and replace STEP by a statement
that multiplies p by x. The parts in red have been added.
int p = 1;
int i = 1;
while(i <= n)
{
p *= x;
i++;
}
That loop ends with p = xn. Let's wrap that up
into a function.
// power(x,n) returns x to power n.
// Requirements: n >= 0 and x != 0.
int power(int x, int n)
{
int p = 1;
int i = 1;
while(i <= n)
{
p *= x;
i++;
}
return p;
}