Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Recursive function to find X to the power n (http://www.go4expert.com/articles/recursive-function-x-power-n-t9307/)

rashida.par 13Mar2008 15:31

Recursive function to find X to the power n
 

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));
    }
}


ismail.tech21 17Mar2008 16:05

Re: Recursive function to find X to the power n
 
nice one

rai_gandalf 8Apr2008 00:15

Re: Recursive function to find X to the power n
 
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 14Apr2008 17:54

Re: Recursive function to find X to the power n
 
i cannot understand this.please do it in an easy way

GAURAV SABOO 21Apr2008 12:36

Re: Recursive function to find X to the power n
 
thank you rashida.you have done it in a very easy way

mikhala 28Apr2008 03:34

Re: Recursive function to find X to the power n
 
How do you do this manually in C++ without using the Power functionality?

wagmare 20May2008 10:25

Re: Recursive function to find X to the power n
 
thats excellent especially the negative sides.... can u help me for me to learn using recursion in C

asadullah.ansari 20May2008 16:30

Re: Recursive function to find X to the power n
 
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


All times are GMT +5.5. The time now is 04:28.