WAP to find x to the power y(xy ) using loop
Objective
Write a C++ program to manually calculate X to the power of Y (XY) using a loop.
Algorithm / Approach
- Read the base
nand the exponentp. - Initialize an accumulator
pow = 1. - Run a
forloop exactlyptimes. - Inside the loop, multiply the accumulator by the base:
pow = pow * n. - Print the final result.
main.cpp
#include<iostream>
using namespace std;
int main() {
int n,p,pow = 1;
cout<<"Enter Base: ";
cin>>n;
cout<<"Enter Power: ";
cin>>p;
for(int i=1;i<=p;i++) {
pow = pow * n;
}
cout<<"Result = "<< pow<< endl;
return 0;
}
Expected Output
Enter Base: 4 Enter Power: 3 Result = 64
Explanation of the Program
- While C++ has a built-in
pow()function, writing it manually is a great way to understand how loops work. - Just like how a factorial accumulates a product of descending numbers, an exponent calculates a product by repeatedly multiplying the EXACT SAME base number against itself.
Complexity
Time Complexity
O(p) - Where p is the exponent.
Space Complexity
O(1)