Let's write a function to calculate the power using a loop, and we will also use the `pow` function from the math library for comparison.
#include <stdio.h>
#include <math.h>
double power(double base, int exponent) {
double result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
double base;
int exponent;
printf("Enter base and exponent: ");
scanf("%lf %d", &base, &exponent);
printf("Using custom function: %.2lf\n", power(base, exponent));
printf("Using pow function: %.2lf\n", pow(base, exponent));
return 0;
}
This program introduces two methods to calculate power, allowing users to understand both the iterative approach and the use of built-in functions.