In computer programming, power is denoted by symbol ^ . To calculate the power y of a number x, we use x^y. For example
Let’s say x = 2, y = 5
Output of x^y = 32.
Below is the implementation of the same
#include<iostream>
using namespace std;
int pow(int x, int y) {
int i,pow_var=1;
if(y == 0)
return 1;
for(i=1;i<=y;i++)
pow_var=pow_var*x;
return pow_var;
}
int main() {
int x = 2;
int y = 5;
cout<<"Number: "<<x<<endl;
cout<<"Power:"<<y<<endl;
cout<<"x^y = "<<pow(x,y);
return 0;
}
Output:
Number:2
Power:5
x^y = 32
In the above program, the function pow() is used to calculate the power of a number x. IIn the pow function, we have use a for loop is used which runs from 1 to power variable(y). For each iteration of the loop, x is multiplied with pow_var to keep multiplying itself till power value.
So, x is multiplied with itself y times and the result is stored in pow_value. This leads to x^y being stored in pow_var and then returned to the main() function.