-->





Recursive function in c++ programming

This c++ tutorial contains
  • What is a recursion?
  • What are its important parts
  • A simple example code
  • How it affects stack
Recursion in c++ programming 
It is one of the most annoying or difficult concept for c++ programming for beginners. Yes it is difficult for a beginner to understand because sometimes its execution goes in depth where things becomes complicated and a beginners feel difficult to understand it.
A function calls it self until a certain condition is true

A recursive function has two important parts
1. Base case, Stopping state, stopping condition
2. Functions call its self with a specific conditions (Recalling condition)

When a function calls occur in a program it pushes into the stack. So if a function is calling itself again and again (Recursive Calling) it will be pushing again and again on the stack every time it will push new resources will be allocated for a new call.

Base Case:

Its a condition when it becomes true or executes function stop to call it self

Recalling Condition:
A condition in which function recalls it  self with a specific parameters or it depends on the required result we want to get.
  • Lets write a simple example to understand the how recursive function works.
  • In this example an integer 'n' is passing to a function in which its value is incrementing by one in recalling condition.
  • When its value becomes 11 or greater than 10 (base case) it returns all calls.



#include<iostream>
using namespace std;
void recursive_function(int n){

       if(n>10)   //base case 
           return;
      else{
           cout<<"Recursive Function call number "<<n<<endl;
           recursive_function(n=n+1)// here function is calling it self
          }
}
int main(){
  int n=1;
  recursive_function(n)// function call
return 0;
}

Its output:
Recursive function in c++ programming sample output of the code





Lets have a look to this program it has a problem what



#include<iostream>
using namespace std;
void recursive_function(){
       cout<<"I am Recursive Function"<<endl;
       recursive_function()// here function is calling it self
}
int main(){
  recursive_function()// function call
return 0;
}

When we run the above code our program get crashes why?
When a function is called it puts on to the stack. In the above program function is calling itself again and again and putting its calls on the stack again and again where stack is reserving some resources for each call.
So the stacks are not in large size and when stack becomes full our program get crashes. This is why because there is not a base case in program where function will stop putting itself on stack.






It is recommended to understand the concept do experiment with the code and analyze the output and also dry run the code on paper.  Another example in c++

3 comments: