Learn recursion for beginners.
Recursion is a function that call itself. It is an important concept. Recursion should must have a base condition that stop it from further calling.
General syntax of recursion.
void fun(int x)
{
// logic
}
int main()
{
fun(x);
return 0;
}
When we call the recursion then printing is done at two time;
- Printing at calling time.
- Printing at returning time.
Printing at calling time:
void fun(int x)
{
if(x>0)
{
printf("%d",x);
fun(x-1);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}
Printing at returning time:
Difference between loop and recursion:
Types of recursion:
- Tail recursion
- Head recursion
- Tree recursion
- Indirect recursion
- Nested recursion
void fun(int x)
{
if(x>0)
{
printf("%d",x);
fun(x-1);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}
2.Head recursion:
3. Tree recursion.
4. Indirect recursion.
In indirect recursion there may be more than one function calling each other in circular fashion.So that the first function calls second one and then second function calls third one and then third function again callback first function.
Then it become a cycle so it become recursion.
5. Nested recursion.
#include<stdio.h>
int fun(int n)
{
if(n>100)
{
return n-10;
}
else
{
return fun(fun(n+10));
}
}
int main()
{
int x = 3;
int d = fun(x);
printf("%d",d);
return 0;
}
0 Comment to "Learn recursion for beginners."
Post a Comment
If you have any doubts then let me know.