x^n using Recursion

problem statement
write a c program which first scans two numbers x and n and then calculates xn using recursion

#include<stdio.h>
int x_pow_n(int x,int n);
int main()
{
  int x,n,y;
  printf("enter x \n");
  scanf("%d",&x);
  printf("enter the value of n \n");
  scanf("%d",&n);
  y=x_pow_n(x,n);
  printf("x^n=%d \n",y);
  return 0;
}
int x_pow_n(int x,int n)
{
  if(n==1)
    {
      return x;
    }
  else
    {
      if(n%2==0)   // even
{
 return x_pow_n(x,n/2)*x_pow_n(x,n/2);
}
      else
{
 return x*x_pow_n(x,n/2)*x_pow_n(x,n/2);
}
    }
}

No comments:

Post a Comment