In this article, we’ll take a look at understanding the power function in C / C++.

The power function computes the power of a base, raised to an exponent number.

Let’s look at this function in a bit more detail, using some examples.

Table of Contents

## Basic Syntax of the Power function in C/C++

The `pow()`

function takes in a base number and an exponent number, and returns the value `base^(exponent)`

.

All of these values are of the type `double`

.

Also, this function is a part of the `<math.h>`

header file, so we must import it first.

#include <math.h> double pow(double base, double exponent);

In case we give an incorrent range for the input, we will get a `NAN`

result.

For example, if `base`

is a negative finite value, and `exponent`

is a finite non-integer, we will get a domain error, since the decimal power of a negative number is a complex number, which is not in the scope of C datatypes.

Let’s take a look at some examples now.

## Using the Power function in C / C++ – Some Examples

Let’s take two integers first, and find the power of them.

#include <stdio.h> #include <math.h> int main() { int base = 3; int exponent = 5; int result = (int) pow(base, exponent); printf("Base = %d, Exponent = %d, Result = %d\n", base, exponent, result); return 0; }

**Output**

Base = 3, Exponent = 5, Result = 242

As you can see, `pow()`

did compute `3^5 = 243`

.

Let’s check it for floating point numbers now.

#include <stdio.h> #include <math.h> int main() { double base = 3.45; double exponent = 5.6; double result = pow(base, exponent); printf("Base = %.4lf, Exponent = %.4lf, Result = %.4lf\n", base, exponent, result); return 0; }

**Output**

Base = 3.4500, Exponent = 5.6000, Result = 1027.5121

Indeed, it seems to work with floating point exponents and bases as well!

Let’s take another example, which will give us a `NAN`

result.

include <stdio.h> #include <math.h> int main() { double base = -1; double exponent = 5.6; double result = pow(base, exponent); printf("Base = %.4lf, Exponent = %.4lf, Result = %.4lf\n", base, exponent, result); return 0; }

**Output**

Base = -1.0000, Exponent = 5.6000, Result = -nan

Here, since `-1^5.6`

is a complex number, it will become a `nan`

value! So you must be very careful to ensure that your input and output aren’t `nan`

values!

## Conclusion

We learned about using `power()`

in C / C++, which is useful to compute the mathematical power of a base, to an exponent.

For similar content, do go through our tutorial section on C programming!

## References

- Linux Manual page on the power() function in C