pow() function.Power of a number = base^exponent
#include <iostream>
using namespace std;
int main()
{
int exponent;
float base, result = 1;
cout << "Enter base and exponent respectively: ";
cin >> base >> exponent;
cout << base << "^" << exponent << " = ";
while (exponent != 0) {
result *= base;
--exponent;
}
cout << result;
return 0;
}Enter base and exponent respectively: 2.7
3
2.7^3 = 19.68353 = 5 x 5 x 5 = 125while (exponent != 0) {
result *= base;
--exponent;
}
result as 1 during the beginning of the program.base == 5 and exponent == 3.| Iteration | result *= base | exponent | exponent != 0 | Execute Loop? |
|---|---|---|---|---|
| 1st | 5 |
3 |
true |
Yes |
| 2nd | 25 |
2 |
true |
Yes |
| 3rd | 125 |
1 |
true |
Yes |
| 4th | 625 |
0 |
false |
No |
However, the above technique works only if the exponent is a positive integer.
If you need to find the power of a number with any real number as an exponent, you can use pow() function.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float base, exponent, result;
cout << "Enter base and exponent respectively: ";
cin >> base >> exponent;
result = pow(base, exponent);
cout << base << "^" << exponent << " = " << result;
return 0;
}Enter base and exponent respectively: 2.5
4.1
2.5^4.1 = 42.8109pow() function to calculate the power of a number.pow() function.pow() function to calculate the power. The first argument is the base, and the second argument is the exponent.