WAP to find x to the power y
Objective
Write a C++ program to calculate X to the power of Y (XY).
Algorithm / Approach
- Include the
<math.h>header. - Declare variables for the base
x, exponenty, and theresult. - Read values for
xandyfrom the user. - Use the built-in power function:
result = pow(x, y). - Print the result.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int x,y,result;
cout<<"Enter Base: ";
cin>>x;
cout<<"Enter Power: ";
cin>>y;
result = pow(x,y);
cout<<"RESULT = "<< result;
return 0;
}
Expected Output
Enter Base: 5 Enter Power: 3 RESULT = 125
Explanation of the Program
- The
pow(base, exponent)function handles complex exponentiation mathematically. - Note:
pow()technically accepts and returns floating-point numbers. Assigning its result directly to an integer variable (like in this code) will implicitly cast it and strip away any decimals, which is fine for whole-number exponents.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)