Section 1.7 of “The
C Programming Language” by Brian
Kernighan and Dennis Ritchie aka K&R
introduces user-defined functions. They first example they give is their power
function. Time to test out their code.
Sample Code.
I am using Visual C++ 2010 and created the sample code as a
console application.
//
Function prototype.
int power(int m, int n);
// The
standard library includes the system function.
#include <cstdlib>
//
Standard I/O library.
#include <cstdio>
int main()
{
int i;
printf("K&R
Section 1.7 Power Function.\n\n");
for (i = 0;
i < 10; ++i)
printf("%d
%d %d\n", i, power(2,i), power(-3,i));
// Keep console
window open.
system("pause");
// Return some
value.
return 0;
} // end main
/*
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;
}
Output.
No comments:
Post a Comment