dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Dec 9, 2002

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Tail Recursion


Tail recursion is a special way of writing recursion in C/C++, which minimizes the time and memory, this can be done just by storing the value of variable in some temporary memory instead of depending on stack for it. Here's an example:
 
/* Factorial with Normal Recursion */
int fact(int n)
{
  if(n<0)
    return 0;
  else
    if(n==0)
      return 1;
  else
      return n*fact(n-1);
}

When run with 4 as value of n fact(4)->4*Fact(3)->3*fact(2)->2*fact(1)->1 1->2*1->3*2->4*6=24
 
/* Factorial with Tail Recursion */

int fact(int n,int a)
{
  if(n<0)
    return 0;
  else
     if(n==0)
        return 1;
     else
        return fact(n-1,n*a);
}

When called with fact(4,1)fact(4,1)->fact(3,4)->fact(2,12)->fact(1,24)->24.
Narla Rajashekar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date