# Recursive function to find X to the power n

Discussion in 'C' started by rashida.par, Mar 13, 2008.

1. ### rashida.parNew Member

Joined:
Feb 14, 2008
Messages:
21
1
Trophy Points:
0

### Introduction

In this i have made use of recursion to calculate x to the power n

Code:
```
#include <stdio.h>

main()
{
float x;

int n;

printf("\n enter values of x an n");

printf("\n %.4f to the power of % d is %.4f",x,n,power(x,n));
}```
Here power is a user defined function the job of this function is to check the values of x and n and either call the function recursively or return back.

Code:
```
float  power(float x, int n)
{

if (x==0)
{
return 0;

}
else if(n==0)
{
return 1;

}
else if (n>0)
{
return( x* power(x,n-1));
}
else
{
return ((1/x)*power(x,n+1));
}
}```

shabbir likes this.
2. ### ismail.tech21New Member

Joined:
Feb 14, 2008
Messages:
18
0
Trophy Points:
0
nice one

3. ### rai_gandalfNew Member

Joined:
Nov 4, 2005
Messages:
46
1
Trophy Points:
0
Occupation:
Final Year Comp Engg
Location:
Mumbai
This is a simple implementation of a standard algorithm & is a classic example of Tail Recursion - the form of recursion which is redundant & can be replaced by a simpler, more efficient iterative equivalent (as Pradeep has done in his article of the same program - click here)

Regards,
Rajiv Iyer

PS: Tail Recursion's classic trademark identification signature is that the recursive calls are usually the last statements within the recursive function's body.

4. ### GAURAV SABOONew Member

Joined:
Apr 13, 2008
Messages:
5
0
Trophy Points:
0
i cannot understand this.please do it in an easy way

5. ### GAURAV SABOONew Member

Joined:
Apr 13, 2008
Messages:
5
0
Trophy Points:
0
thank you rashida.you have done it in a very easy way

6. ### mikhalaNew Member

Joined:
Apr 27, 2008
Messages:
1
0
Trophy Points:
0
How do you do this manually in C++ without using the Power functionality?

7. ### wagmareNew Member

Joined:
May 14, 2008
Messages:
11
0
Trophy Points:
0
Occupation:
soft.engg
Location:
Bangalore
thats excellent especially the negative sides.... can u help me for me to learn using recursion in C

Joined:
Jan 9, 2008
Messages:
356