A function can call each and every function that exists in the program. But when a function call itself then this process is known as Recursion. It may be called Directly or Indirectly.
Why Recursion ?
The main work of recursion is to execute the similar statements like we do in iterative statements, but then why we use recursion in place of iterative statements?
- Sometimes we don't know that for how many times we want our loop to execute itself, then to overcome this problem we use recursion.
- We also use recursion to increase the simplicity if the code which may become complex if they were written using iteration statements.
- Recursion also reduces the unnecessary calling of the function.
There are two important things a recursion function should have:
- Function should call itself again and again.
- The function should contain an exit condition.
Flow Chart |
Types of Recursion
There are two types of recursion- Direct Recursion & Indirect Recursion
Direct Recursion:
When a function calls itself directly i.e, if a function calls the same function inside it then this is called Direct Recursion.
Syntax: func( )
{
................
................
................
func( );
................
................
}
Let understand it by an example:-
@ Write a program to display even numbers between 1 to 10 using direct recursion ?
@ Write a program to display even numbers between 1 to 10 using direct recursion ?
Example 1 |
Here main( ) function is calling itself directly.
OUTPUT |
Indirect Recursion:
When a function calls itself by the help of another function i.e, the function call happens on the another function.
Syntax: main( )
{
..............
..............
..............
func( );
..............
..............
}
func( )
{
..............
..............
}
Let see an example regarding it:-
@ Write a program to find out the factorial of '12' using indirect recursion ?
@ Write a program to find out the factorial of '12' using indirect recursion ?
- Recursive programs are generally slower than non recursive programs because it needs to make a function call so the program must save all its current state and retrieve them again later. This consumes more time making recursive programs slower.
- Recursive programs requires more memory to hold intermediate states in a stack( memory ). Non recursive programs don't have any intermediate states, hence they don't require any extra memory.
To read our post on Function, please click on FUN( ).
To read our post on Array (Part-1) please click on Arr1.
To read our post on Array (Part-1) please click on Arr1.
For giving some suggestion please comment us or check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog. Thank you for your support and time...
0 Comments