ch1-power function

Chapter_1     Exercise_1-14-2 Exercise_1-15







power.c     K&R, p. 24-25         download


#include <stdio.h> // for printf()

int power(int m, int n); // returns m to power n
// int power(int, int); // alternative declaration

// test power() function

int main()
{
int i;

for (i = 0; i < 10; i++)
{printf("%d %d %d\n", i, power(2,i), power(-3,i));}

return 0; // normal return value for main(), signals no errors
}

// power(): raise base to n-th power; n >= 0
int power(int base, int n)
{
int i, p;

p = 1; // base to power 0 is 1
for (i = 1; i <= n; i++)
{p *= base;} // p = p * base;

return p;
}
/*
gcc power.c -o power
./power
0 1 1
1 2 -3
2 4 9
3 8 -27
4 16 81
5 32 -243
6 64 729
7 128 -2187
8 256 6561
9 512 -19683
*/









Chapter_1     Exercise_1-14-2 BACK_TO_TOP Exercise_1-15



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo