English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Using C ++Writing Power (Power) Function

The power function is used to find the power of two given numbers (base and exponent). The result is the base raised to the power of the exponent.

An example that demonstrates this point is as follows-

Base = 2
Exponent = 5
2^5 = 32
Hence, 2 raised to the power 5 is 32.

Demonstration C ++The program for the power function is as follows-

Example

#include
using namespace std;
int main(){
   int x, y, ans = 1;
   cout << "Enter the base value: \n";
   cin >> x;
   cout << "Enter the exponent value: \n";
   cin >> y;
   for(int i = 0; i < y;++)
   ans *= x;
   cout << x << " raised to the power " << y << " is " << ans;
   return 0;
}

Example

The output of the above program is as follows-

Enter the base value: 3
Enter the exponent value: 4
3 raised to the power 4 is 81

Now let's understand the above program.

The values of the base and exponent are obtained from the user. The code snippet to do this is as follows-

cout << "Enter the base value: \n";
cin >> x;
cout << "Enter the exponent value: \n";
cin >> y;

The power is calculated using a for loop, which runs until the exponent value. In each iteration, the base value is multiplied by ans. After the for loop is completed, the final power value is stored in the variable ans. The code snippet to do this is as follows-

for(int i = 0; i < y;++)
ans *= x;

Finally, display the power value. The code snippet to do this is as follows-

cout << x << " raised to the power " << y << " is " << ans;