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. Look at the output:
- base number = 3
- exponent = 4
#include <iostream> #include <cmath> using namespace std; int main() { // base 3 and exp = 4 cout << pow(3, 4); return 0; }
Output:
An example of using C++ pow() function with two floats
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:
#include <iostream> #include <cmath> using namespace std; int main() { float x,y; x = 5.5f; y = 3.5f; // base 5.5 and exp = 3.5 cout <<"The result = " << pow(x, y); return 0; }
Output:
Calculating exponent by using for loop example
As mentioned earlier, you may write your logic rather than using the pow() built-in function. In the program below, we used a for loop to get the exponent:
#include <iostream> using namespace std; int main() { int base, exponent, res=1; //Taking user input for base and exp values cout << "Enter base value: "; cin >> base; cout << "Enter exponent value: "; cin>>exponent; //For loop logic to calculate for (int i = 1; i <=exponent; i++) { res=res*base; } //Display final result cout <<base<<" ^ "<<exponent<<" = "<<res<<endl ; }
Sample Output:
Using a 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:
#include <iostream> using namespace std; int main() { int base, exponent, res=1; int i = 1; //Taking user input for base and exp values cout << "Enter base value: "; cin >> base; cout << "Enter exponent value: "; cin>>exponent; //While loop logic to calculate while (i <=exponent) { res=res*base; i++; } //Display final result cout <<base<<" ^ "<<exponent<<" = "<<res<<endl ; }
Sample Output:
As we entered two integer values for base and exponent i.e. 5 and 3, respectively, we get the result 125.