![]() |
![]() |
![]() |
![]() |
![]() |
|
Now you can define the power_of_2 function using a for loop
instead of a while loop. The initialization expression,
counter = n, assigns the value of the parameter n to
counter. Then, as long as the value of counter is not 0, the
value of result, whose initial value is 1, is multiplied by 2 and
the value of counter is decremented by 1.
int power_of_2 (int n) {
int counter, result = 1;
for (counter = n; counter; counter = counter - 1)
result = 2 * result;
return result;
}