In this example, the mechanics of function definition are illustrated by writing a function, power(m,n)
, to raise an integer m
to a positive integer power n
.
#include <stdio.h>
int power(int m, int n);
// test power function
int main(int argc, const char * argv[]) {
int i;
for (i = 0; i < 10; ++i) {
printf("%d %d %dn", i, power(2, i), power(-3, i));
}
return 0;
}
// power: raise base to n-th power: n >= 0
int power(int base, int n) {
int i, p;
p = 1;
for (i = 1; i <= n; ++i) {
p = p * base;
}
return p;
}
The trouble I’m having is learning, exactly, what the variables, in the power(int base, int n)
function definition, represent.
I understand what the program is trying to do, which is display the powers of 2
and (-3)
, using the numbers 0-9, as exponents.
However, I’m not understanding how the program goes about doing that.
For example, in power(int base, int n)
, does the p
variable represent the “power” of 2^0
, or 2^1
. . . until, 2^9
?
Likewise, for the second callback function, does the p
variable represent the “power” of (-3)^0
, or (-3)^1
. . . until, (-3)^9
?
For example, in power(int base, int n)
, does the i
variable represent the “exponent”, in that, during the first loop, of power(int base, int n)
, when n
is 0
(! <= n)
, the body of for
isn’t evaluated, and p
remains the same (1)
, b/c any nonzero number raised to the power of 0
equals 1
?
By the time n
is assigned the value of 9
, for
is going to be looping through numbers 1-9
, mimicking the number of times you multiply the base, by itself (exponentiation), giving you the “power” of that number.
Do I have any of this right? Any ideas as to where one could learn how to identify what variables, in programs, represent?
Is seeing how the variables change value, in the debugger, the best way to learn how to identify what the variables, in programs, represent, or is there another/better way?
Any feedback would be appreciated! Feel free to ask me to clarify, anything.
Thanks!