Syntax
double pow(double base, double exp);
The pow() function is defined in math.h header file.
Arguments
This function takes two arguments, base and exp, to calculate the value of base raised to the power of exp. Here base and exp both are double.
Return values
On success, the pow() function returns the value of base raised to the power of exp.
If the value of exp is 0, the pow() function returns 1.
If base is negative and exp is non integral, the pow() function returns NaN (Not-A-Number).
Examples
#include
#include
int main()
{
int result;
result = (int)pow(3,5);
printf("\npow(3,5) => %d",result);
printf("\npow(3,-5) => %lf",pow(3,-5));
printf("\npow(-3,-5) => %lf",pow(-3,-5));
printf("\npow(3,5.1) => %lf",pow(3,5.1));
printf("\npow(-3,5.1) => %lf",pow(-3,5.1));
printf("\npow(-3,-5.1) => %lf\n",pow(-3,-5.1));
return 0;
}
In Example1.c, we have seen the output of the pow() function. Here we use the -lm command line parameter to link in the math library. From lines 10 to 13, we have got the output as expected. For lines 14 and 15, we have got -nan(Not a number) because the second argument is not integral.
Exponent using Bit Shifting
If we want to calculate the exponent to the power of 2, then we can do it using bit shifting.
The left shift by m is equivalent to the first term and 2 to the power m.
n << m = n*pow(2,m)
The right shift by m is equivalent to the division of the first term and 2 to the power m.
n>>m = n/pow(2,m)
It is only work when m is positive.
In Example2.c, we have seen how the bit shift operator can be used for the exponent to the power of 2. It is very useful to reduce the complexity of the code.
Exponent using User-defined function
We can write a user-defined function to calculate exponents. In Example3.c, we will write a user-defined function exponent (), which takes two arguments based and exp of type float ant integer.
#include
float exponent(float base, int exp)
{
float result =1.0;
float i;
if(exp < 0)
{
exp = -1 * exp;
for(i=1;i<=exp;i++)
result = result * base;
result = 1.0/result;
}
else
{
for(i=1;i %f",exponent(3,0));
printf("\nexponent(3,-5) => %f",exponent(3,-5));
printf("\nexponent(-3,-5) => %f",exponent(-3,-5));
return 0;
}
Example3.c we have seen the output of the user-defined function exponent (). This function is worked when the exponent is integral. For real exponent, we have to use the pow() function.
Conclusion
In this article, we have seen using the pow() function and Bit shifting operator how exponent can be calculated in C language. We also have learned how to write our own function to calculate exponents. Now we can use these techniques in our C program without any doubt.