Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to calculate power of a given number
In C programming, calculating the power of a number means multiplying the base number by itself for a specified number of times (exponent). For example, 34 = 3 × 3 × 3 × 3 = 81. We can implement this using loops or the built-in pow() function.
Syntax
// Manual calculation using loop result = base^exponent // Using pow() function #include <math.h> double pow(double base, double exponent);
Method 1: Using While Loop
This approach uses a while loop to multiply the base value repeatedly −
#include <stdio.h>
int main() {
int base, exponent;
long result = 1;
int i;
printf("Enter base: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
i = exponent;
while (i != 0) {
result *= base;
i--;
}
printf("%d^%d = %ld<br>", base, exponent, result);
return 0;
}
Enter base: 3 Enter exponent: 4 3^4 = 81
Method 2: Using pow() Function
The pow() function from math.h library can handle both integer and floating-point calculations −
#include <stdio.h>
#include <math.h>
int main() {
double base, exponent, result;
printf("Enter base: ");
scanf("%lf", &base);
printf("Enter exponent: ");
scanf("%lf", &exponent);
result = pow(base, exponent);
printf("%.2lf^%.2lf = %.2lf<br>", base, exponent, result);
return 0;
}
Enter base: 2.5 Enter exponent: 3.0 2.50^3.00 = 15.63
Method 3: Using Recursion
We can also implement power calculation using recursive function −
#include <stdio.h>
int power(int base, int exp) {
if (exp == 0)
return 1;
else
return base * power(base, exp - 1);
}
int main() {
int base, exponent, result;
printf("Enter base: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
result = power(base, exponent);
printf("%d^%d = %d<br>", base, exponent, result);
return 0;
}
Enter base: 5 Enter exponent: 3 5^3 = 125
Comparison
| Method | Time Complexity | Use Case | Advantages |
|---|---|---|---|
| While Loop | O(n) | Integer powers | Simple, no library needed |
| pow() Function | O(log n) | Real numbers | Handles decimals, optimized |
| Recursion | O(n) | Educational purpose | Elegant, easy to understand |
Conclusion
For integer calculations, the loop method works well. For real numbers or when performance matters, use the pow() function. The recursive approach is useful for understanding the concept but may cause stack overflow for large exponents.
