The pow() function in C is used to calculate the value of a number raised to a given power. It is defined in the <math.h> header file and returns the result of baseexponent.
- It is commonly used for mathematical and scientific calculations.
- It supports double, float, and long double data types.
#include <stdio.h>
// Include math.h for the pow() function
#include <math.h>
int main() {
double base = 5, exponent = 3, result;
// Calculate the result of base
// raised to the power of exponent
result = pow(base, exponent);
// Output the result
printf("%.0f raised to the power of %.0f is %.0f\n", base, exponent, result);
return 0;
}
Output
5 raised to the power of 3 is 125
Note: To use the pow() function, include the <math.h> header file in the program.
Syntax
double pow(double base, double exponent);
Parameters:
- base: Number to be raised
- exponent: Power value
Return Value:
- The function returns the value of, baseexponent
Example: Using pow() with Double Values
#include <stdio.h>
#include <math.h>
int main()
{
//taking double as input
double x = 6.176, y = 4.832;
printf("%f raised to power of %f is %f\n", x, y, pow(x, y));
//taking float as input
float a = 3.14, b = 2.58;
printf("%f raised to power of %f is %f\n", a, b, pow(a, b));
//taking long double as input
long double p = 2.1591, q = 2.8642;
printf("%Lf raised to power of %Lf is %f\n", p, q, pow(p, q));
return 0;
}
Output
6.176 raised to power of 4.832 is 6617.56 3.14 raised to power of 2.58 is 19.146 2.1591 raised to power of 2.8642 is 9.06617
Example: Using pow() with Float Values
#include <stdio.h>
#include <math.h>
int main() {
float a = 3.14, b = 2.58;
printf("%f raised to power of %f is %f",
a, b, pow(a, b));
return 0;
}
Output
3.140000 raised to power of 2.580000 is 19.146019
pow() Function with Integers
The pow() function returns a double value, so integer results may sometimes produce inaccurate outputs due to floating-point precision issues.
For example:
pow(5, 2)
may internally store: 24.9999999
instead of: 25
When converted directly to int, it may produce incorrect results on some compilers.
Correct Way to Use pow() with Integers
We can solve this issue using:
- Typecasting with 1e-9
- round() function
Example: pow() with Integers
#include <math.h>
#include <stdio.h>
int main()
{
int a, b;
// Using typecasting for
// integer result
a = (int)(pow(5, 2) + 1e-9);
b = round(pow(5,2));
printf("%d \n%d", a, b);
return 0;
}
Output
25 25
Time Complexity: O(log(n))
Auxiliary Space: O(1)