top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to implement pow(x, y) in C/C++ which should return x^y. Please provide both iterative and recursive way?

+3 votes
481 views
How to implement pow(x, y) in C/C++ which should return x^y. Please provide both iterative and recursive way?
posted Oct 12, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Iterative method

#include<stdio.h>
int main()
{
  double x,y,i;
  scanf("%d%d",&x,&y);

  for(i=1;i<y;i++)
    x=x*x;

  printf("%d",x);
  return 0;
}

Recursive Method

#include<stdio.h>
int pow(int x,int y)
{
    if(y==1)
    return x;
    else
    return x*pow(x,--y);
}

int main()
{
  int x,y;
  scanf("%d%d",&x,&y);
  x=pow(x,y);
  printf("%d",x);
  return 0;
}
answer Dec 9, 2015 by Rajan Paswan
What if power is not an integer i.e. 2^4.23 here y is 4.23 ??
Similar Questions
+5 votes

Say I have a function which is written in recursive way which is costly way of doing the things. Now I want to convert the recursive function into iterative one. Is there a standard approach which can be applied to all the functions..

...