I am stuck with this line of the code from the "C Programming Language" book - "for (p = 1; n > 0; --n)" - the counter runs from 1 to more than 1, while step is -1. but what is the counter? n itself?
(I used to see for (i = 1; i <= n; ++i)-like structures, so the issue of counter was clear, however in version 2 I encountered that I don't really know what and where the counter is...
From here:
/* power: raise base to n-th power; n >= 0; version 2 */
int power(int base, int n)
{
int p;
for (p = 1; n > 0; --n)
p = p * base;
return p;
}
In each iteration n
decrements by 1
because of --n
, when n
decrease to 0
condition n > 0
becomes false and loop breaks.
for (p = 1; n > 0; --n)
^
| When n = 0, condition becomes 0 > 0 that is false
In loop you are multiply p = p * base;
evaluates => base * base * base * ...n times
=> basen.
p
is is for store result at the end p = basen.
You may like to write it like (a small code, I think bit fast too):
int p;
for (p = 1; n-- && (p*=base) ;)
return p;
Edit: comments & answers:
for (p = 1; n > 0; --n)
- when the counter starts?
Yes n
is counter, in for loop we don't need to initialized n
. We just initializes p
variable with 1
to store result. Value of n
comes from function argument. you call your int power(int base, int n);
function some where in main, like:
result = power(3,2); // here base = 3, and n = 2
or
result = power(5,7); // here base = 5, and n = 7
from n to p (to 1)?
Loop runs for n
to 1
times (not condition is > 0
) e.g
In first example when you call power(3,2);
, loop runs for n
= 2
to 1
.
likewise in second call of function power(5,7);
loop runs for n
= 7
to 1
.
Why we need p here?
As I have written above in my answer p
we need to store result. e.g.
in loop p
initially 1
, but in each iteration you multiply p
with base
value and store result back to p
only. e.g.
for function call power(3,2);
loop runs and p
calculate like:
base = 3 , n = 2 p = 1; // initialize
First iteration:
condition n > 0 is True because n is 2 (2 > 0).
p = p * base = 1 * 3 = 3
and p becomes 3.
Now --n decreases n to 1
Second iteration:
condition n > 0 is True because n is 1 (1 > 0).
p = p * base = 3 * 3 = 9
and p becomes 9.
Now --n decreases n to 0
third iteration:
condition n > 0 is False because n is 0 (0 > 0).
condition false so loop breaks
return p
that is 32 = 9
.