Recursion
Recursion
Recursion
C prog
Recursion Recursion is the technique of making a function
call itself. This technique provides a way to break
complicated problems down into simple problems
which are easier to solve.
Basic Syntax of Recursion Base (exit) case: When you write a recursive method or
function, it keeps calling itself, so the base case is a specific
condition in the function. When it is met, it terminates the
recursion. It is used to make sure that the program will
terminate. Otherwise, it goes into an infinite loop.
void recursive_fun() //recursive function Recursive case: The part of code inside the recursive function
{ executed repeatedly while calling the recursive function is
Base_case; // Stopping Condition known as the recursive case.
int main()
{
}
Types of Recursion in C
There are two types of recursion in the C language.
function_01() 1.Direct Recursion
{ 2.Indirect Recursion
//some code
function_01();
//some code 1. Direct Recursion
} Direct recursion in C occurs when a function calls itself
directly from inside. Such functions are also called direct
recursive functions.
function_01()
{
//some code
function_02();
2. Indirect Recursion
}
Indirect recursion in C occurs when a function calls another
function and if this function calls the first function again. Such
function_02()
functions are also called indirect recursive functions.
{
//some code
function_01();
}
C Program Function to show indirect recursion
2 1 4 3 6 5 8 7 10 9
#include <stdio.h>
int main() { 55
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else { 10 + sum(9)
return 0; 10 + ( 9 + sum(8) )
} 10 + ( 9 + ( 8 + sum(7) ) )
} ...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
C program to calculate factorial of a number using recursion
#include<stdio.h>
int main()
{
int a,fact;
fact = factorial(a);
printf("Factorial of %d = %d",a,fact);
return 0;
}
int factorial(int n)
{
if(n == 0)
return 1;
else
return (factorial(n-1)*n);
}
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: