Functions: a complete example using prototypes
Comments and questions to John Rowe.
The following example is intended to show main() calling a function
that in turn calls another function:
- main() calls the function printexp(double x, int j)
whose job is to print out x to the power j.
- printexp() in turn calls mypow() to do the
actual calculation.
#include <stdio.h>
double mypow(double base, int exponent);
void printexp(double x, int j);
int main() {
double base = 5.3;
int n = 2;
printexp(base, n);
return 0;
}
void printexp(double base, int j) {
if ( base == 0.0 && j < 0 ) {
printf("Invalid values to printexp\n");
return;
}
printf("%f to the power %d is %f\n", base, j,
mypow(base, j));
}
double mypow(double base, int exponent) {
double result = 1.0;
if (base == 0.0 && exponent < 0 )
return 0.0;
while (exponent > 0) {
result *= base;
--exponent;
}
while (exponent < 0) {
result /= base;
++exponent;
}
return result;
}
Step through this code
Log in