Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find x to the power y (xy) using loop

C Code Example — Loop Programs

ADVERTISEMENT

C Program to find x to the power y (xy) using loop

Objective

Write a C program to find x raised to the power of y (xy) using a loop.

Algorithm / Approach

  1. Read the base x and exponent y from the user.
  2. Initialize a result variable res = 1.
  3. Run a for loop from 0 up to y - 1.
  4. Inside the loop, repeatedly multiply the result by the base: res = res * x.
  5. Print the result.
main.c
#include<stdio.h>
int main( ) {
 int x,y,res=1,i;
 printf("X : ");
scanf("%d",&x);
printf("Y : ");
scanf("%d",&y);
for(i=0; i < y; i++)
{
res = res*x;
}
printf("X^Y IS : %d\n",res);
return 0;
}

Expected Output

X : 8
Y : 2
X^Y IS : 64

Explanation of the Program

  • Instead of using the built-in pow() function from math.h, this program manually calculates the power.
  • Exponentiation is simply repeated multiplication. If y is 3, the loop runs 3 times, multiplying the base by itself exactly 3 times (x * x * x).

Complexity

Time Complexity O(y) - Loop runs y times.
Space Complexity O(1)
ADVERTISEMENT