recursion

As we know, the function always calls its definition. But in the recursion the function calls itself.

This method of function calling is called recursion and the function call is called a recursive function.

Here is the diagram,

recursion

In above diagram, the names of all three functions (function-name) will be the same.

It behaves like a loop in a way i.e. body of function and function call are together. In recursion, the function definition calls itself again when the given condition is true, the function terminates as soon as the condition is false.

SYNTEX:

function_name(parameter_list) // function definition
{
   Body of function;
   function_name(parameter_list);. // calling function
}

Here is an example

void table(int); // function prototype
  .............
  .............

void table(int n) // function definition 
 { 
   Body of function; 
   table(n);. // recursive function
}

Example:-

In this program, the function will call itself until the given condition becomes false i.e. the input (int type) given by the user becomes equal to 0.

#include<iostream.h>
#include<conio.h>

void table(int); // function declaration

void main()
{
   clrscr();
   int num; // variable declaration

   cout<<"Enter a number: ";
   cin>>num;

   recursn(num); // function calling

   getch();
}

 void table(int n) // function definition
 {
   cout<<n<<" ";
   n--;    // value decrease 1 by 1
   
   if(n!=0)            // condition check
     recursn(n); // function call itself
 }
OUTPUT:-
Enter a number: 5
5 4 3 2 1

Here is another example of recursion where we create a table, let’s try this

 


create a table using recursive function

#include<iostream.h>
#include<conio.h>

void table(int,int);

void main(void)
{
   int n,i=1;

   cout<<"Enter number: ";
   cin>>n;

   table(n,i); // function calling with two argument(n,i)

 getch();
}

void table(int x,int y)
{
    for(int i=y; i<=10; i++)
        cout<<x*i<<endl;

   if(i<=10)    // recursive function call until condition false
        table(x,i);
}
OUTPUT:-
Enter number: 3
3
6
9
12
15
18
21
24
27
30

more about function,


previous-Memory Management and Types

next-String library function and theirs examples