Hit enter after type your search item

4 C++ Programs to get exponent (pow() and for loop)

How to get exponent value in C++?

In C++, you may use the built-in function pow() or write your own logic to get the exponent value.

In this tutorial, we will show you different ways of calculating the exponents in C++.

Get exponent by pow() function

The first and easiest way of finding the exponent is using the pow() function.

  • The pow() function is defined in the cmath header So, you have to include this in the header section.
  • The pow() function takes two arguments
  • It returns the base raised to the power (see the syntax below)

Syntax of pow()

double pow(double b, double e);

float pow(float b, float e);

long double pow(long double b, long double e);

where

  • b is the base value.
  • e is the exponent

A simple example of pow() function

We passed two numbers of integer types to the pow() function and see the output:

  • base number = 3
  • exponent = 4


Output:

81

An example of using C++ pow() function with two float

In this example, we provided two values to the pow() function to get the exponent. For that, two variables with float type are declared and assigned values. Have a look:


Output:

Calculating exponent by using for loop example

As mentioned earlier, you may write your own logic rather than using the pow() built-in function. In the program below, we used a for loop to get the exponent:


Sample Output:

CPP-pow-for-loop

Using while loop to get the exponent

Similarly, you may use the while loop to get the exponent as we have done with the for loop. See the example and a sample output below:


Sample Output:

CPP-pow-while-loop

As we entered two integer values for base and exponent i.e. 5 and 3, respectively, we get the result 125.

This div height required for enabling the sticky sidebar