Use a Loop or pow() Function
In this step, you will learn two methods to calculate powers in C: using a manual loop and using the built-in pow()
function from the math library.
First, let's modify the previous power_calculation.c
file to implement power calculation:
cd ~/project
nano power_calculation.c
Method 1: Using a Loop
#include <stdio.h>
int calculate_power_loop(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
int base, exponent;
printf("Enter the base number: ");
scanf("%d", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
int power_result = calculate_power_loop(base, exponent);
printf("%d raised to the power of %d is: %d\n", base, exponent, power_result);
return 0;
}
Method 2: Using pow() Function
#include <stdio.h>
#include <math.h>
int main() {
int base, exponent;
printf("Enter the base number: ");
scanf("%d", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
// Note: pow() returns a double, so we cast to int
int power_result = (int)pow(base, exponent);
printf("%d raised to the power of %d is: %d\n", base, exponent, power_result);
return 0;
}
Compile the program with the math library:
gcc power_calculation.c -o power_calculation -lm
Example output:
Enter the base number: 2
Enter the exponent: 3
2 raised to the power of 3 is: 8
Code Explanation:
- Loop method manually multiplies the base by itself
exponent
times
pow()
function from math.h
provides a built-in power calculation
-lm
flag is required to link the math library when compiling
- We cast
pow()
result to int
to match our integer calculation