Physics and Astronomy
Home Our Teaching Resources C programming A short example

# Functions: a complete example using prototypes

The following example is intended to show main() calling a function that in turn calls another function:

1. main() calls the function printexp(double x, int j) whose job is to print out x to the power j.
2. printexp() in turn calls mypow() to do the actual calculation.
```//
// Demonstrate function prototypes
//
#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;
}

//
// Print out x to the power j, warning if x and j are invalid
//
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));
}

//
// Return base to the power of exponent.
// If base == zero and exponent < zero, return zero
//
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

```