C Program to find x to the power y (xy)
Objective
Write a C program to calculate x raised to the power of y (xy).
Algorithm / Approach
- Include
#include <math.h>. - Declare integer variables
x,y, andres. - Read the base
xand the exponentyfrom the user. - Use the built-in
pow(x, y)function to calculate the result. - Print the result.
main.c
#include<stdio.h>
#include<math.h>
int main( ) {
int x,y,res;
printf("Enter Values for X & Y : ");
scanf("%d%d",&x,&y);
res = pow(x,y);
printf("X^Y IS : %d\n",res);
return 0;
}
Expected Output
Enter Values for X & Y : 4 3 X^Y IS : 64
Explanation of the Program
- The
pow()function frommath.htakes two double arguments and returns the result of the first argument raised to the power of the second. - Even though we passed integers to it, C automatically implicitly casts them to doubles before passing them to the function, and then implicitly casts the double result back to an integer when storing it in
res.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)