C++ recursive function

In a programming language, a recursive function is special function that can call itself to perform subsequent tasks. The recursive function must have a base case. Omitting the base case results in infinite call.

int fact(n){ //without base case=>infinite call

   return n*fact(n-1);
}

The code above should be modified to include the base case(n=0) so that it can calculate factorial value:
int fact(n){ //base case: n=0

      if(n==0) return 1;
     return (n*fact(n-1));
}

Another example is to use recursive function to calculate the following mathematic expression:

E=1+2+3+...+n

int sum(int in){

   if(n==1) return 1;

  else return(n+sum(n-1)); 

}

Posted by: tory | post date: 12-08-2012 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.