Skip to main content

ProwessApps

Learn · Practice · Excel

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

C Code Example — Basic Programs

ADVERTISEMENT

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

  1. Include #include <math.h>.
  2. Declare integer variables x, y, and res.
  3. Read the base x and the exponent y from the user.
  4. Use the built-in pow(x, y) function to calculate the result.
  5. 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 from math.h takes 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)
ADVERTISEMENT