Recursion

What is it ?

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).

b4           = 4 * b3
             = 4 * (3 * b2)
             = 4 * (3 * (2 * b1))
             = 4 * (3 * (2 * (1 * b0)))
             = 4 * (3 * (2 * (1 * 1)))
             = 4 * (3 * (2 * 1))
             = 4 * (3 * 2)
             = 4 * 6
             = 24

Why recursion?

Where it's useful?

Let's see what notion do you have?

Function 1

void recursiveFunction(int num) {
   printf("%d\n", num);
   if (num < 4)
      recursiveFunction(num + 1);
}

Function 2:

void recursiveFunction(int num) {
   if (num < 4)
      recursiveFunction(num + 1);
   printf("%d\n", num);
}

Iterative approach involves four steps, initialization , condition, execution and  updation.

 

 

In recursive function, only base condition (terminate condition) is specified.

#include<iostream>
using namespace std;
void combination(int i,int data[],int r,int n)
{ 
if(i==r) {
for(int k=1;k<=i;k++) cout<<data[k]<<" ";
cout<<"\n";
return ;
}
for(int j=1;j<=n;j++)
{ 
data[i+1]=j;
combination(i+1,data,r,n);
}
}
int main() {
int r,n;
r=3;
n=3;
int data[r+1];
combination(0,data,r,n);
return 0;
}

Print all possible combinations of r elements in a given array 

Copy of deck

By Khushboo Gupta

Copy of deck

  • 894