C++ Recursion

October 27, 2015 Posted by WithU Technologies
Recursion is a function which we create manually to call that function by itself.

Recursion process is similar to for loop or while loop where the loop runs again and again within a specific number of times.

And as like loop we must include a termination condition or else it will run indefinitely.

Using for loop:

#include <iostream>
#include <stdlib.h>
using namespace std;

void loopNumber(int a){

      cout<<"The number is: "<<a<<endl;

}

int main(){

      for(int x=1;x<5;x++){

            loopNumber(x);

      }

}
/*

Outputs

The number is: 1

The number is: 2

The number is: 3

The number is: 4

*/
·         Here a function is declared first, named as loopNumber and then the function is defined to output a message along with the integer value of a provided by the main function.

·         The program is first started with the main function where a for loop is declared which is conditioned to create output for 4 times.

·         And in output it calls the loopNumber function.

Using recursion method:

#include <iostream>
#include <stdlib.h>
using namespace std;

void loopNumber(int a){

      cout<<"The number is: "<<a<<endl;

      a++;

      if (a<5){

            loopNumber(a);

 }

}

int main(){

      int r = 1;

      loopNumber(r);

      return 0;

}

/*

Outputs

The number is: 1

The number is: 2

The number is: 3

The number is: 4

*/

·         Here instead of using for loop in the main function, we use recursion loop to create the same condition within that loopNumber function which will ultimately generate the same output.

·         The main function started with the program and it initializes integer r started with a value of 1 which acts as the starting position of recursion loop.

·         Then it calls the loop number function, thus the loopNumber function output a message first along with the first loop number.

·         Then it increments the loop number and then it checks the condition and it the condition is fulfilled, it again calls the function.

·         A base case is always necessary for a real recursion to avoid the recursion to run infinite number of times.