Recursive function to find X to the power n

rashida.par's Avatar author of Recursive function to find X to the power n
This is an article on Recursive function to find X to the power n in C.
Rated 5.00 By 17 users

Introduction



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

Code: Cpp
#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: Cpp
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 like this
ismail.tech21's Avatar, Join Date: Feb 2008
Go4Expert Member
nice one
rai_gandalf's Avatar, Join Date: Nov 2005
Go4Expert Member
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.
GAURAV SABOO's Avatar, Join Date: Apr 2008
Light Poster
i cannot understand this.please do it in an easy way
GAURAV SABOO's Avatar, Join Date: Apr 2008
Light Poster
thank you rashida.you have done it in a very easy way
mikhala's Avatar, Join Date: Apr 2008
Newbie Member
How do you do this manually in C++ without using the Power functionality?
wagmare's Avatar, Join Date: May 2008
Go4Expert Member
thats excellent especially the negative sides.... can u help me for me to learn using recursion in C
asadullah.ansari's Avatar, Join Date: Jan 2008
TechCake
Quote:
Originally Posted by wagmare
thats excellent especially the negative sides.... can u help me for me to learn using recursion in C
You can check this thread
http://www.go4expert.com/showthread.php?t=10396