Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find x to the power y(xy ) using loop

C++ Code Example — Loop Programs

ADVERTISEMENT

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

  1. Read the base n and the exponent p.
  2. Initialize an accumulator pow = 1.
  3. Run a for loop exactly p times.
  4. Inside the loop, multiply the accumulator by the base: pow = pow * n.
  5. 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)
ADVERTISEMENT