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
- Read the base
xand exponentyfrom the user. - Initialize a result variable
res = 1. - Run a
forloop from0up toy - 1. - Inside the loop, repeatedly multiply the result by the base:
res = res * x. - 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 frommath.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)