power program from the book "c program. lang." version2, cycle -
i stuck line of code "c programming language" book - "for (p = 1; n > 0; --n)" - counter runs 1 more 1, while step -1. counter? n itself?
(i used see for (i = 1; <= n; ++i)-like structures, issue of counter clear, in version 2 encountered don't know , counter is...
from here:
/* power: raise base n-th power; n >= 0; version 2 */ int power(int base, int n) { int p; (p = 1; n > 0; --n) p = p * base; return p; }
in each iteration n decrements 1 because of --n, when n decrease 0 condition n > 0 becomes false , loop breaks.
for (p = 1; n > 0; --n) ^ | when n = 0, condition becomes 0 > 0 false in loop multiply p = p * base; evaluates => base * base * base * ...n times => basen.
p is store result @ end p = basen.
you may write (a small code, think bit fast too):
int p; (p = 1; n-- && (p*=base) ;) return p; edit: comments & answers:
for (p = 1; n > 0; --n)- when counter starts?
yes n counter, in loop don't need initialized n. initializes p variable 1 store result. value of n comes function argument. call int power(int base, int n); function in main, like:
result = power(3,2); // here base = 3, , n = 2 or
result = power(5,7); // here base = 5, , n = 7 from n p (to 1)?
loop runs n 1 times (not condition > 0) e.g
in first example when call power(3,2);, loop runs n = 2 1. likewise in second call of function power(5,7); loop runs n = 7 1.
why need p here?
as have written above in answer p need store result. e.g.
in loop p 1, in each iteration multiply p base value , store result p only. e.g.
function call power(3,2); loop runs , p calculate like:
base = 3 , n = 2 p = 1; // initialize
first iteration:
condition n > 0 true because n 2 (2 > 0). p = p * base = 1 * 3 = 3 , p becomes 3. --n decreases n 1 second iteration:
condition n > 0 true because n 1 (1 > 0). p = p * base = 3 * 3 = 9 , p becomes 9. --n decreases n 0 third iteration:
condition n > 0 false because n 0 (0 > 0). condition false loop breaks return p 32 = 9.
Comments
Post a Comment