Recursion in C
Recursion in C
Recursion in C
Definition (Mathematical)
10-6
Example: multiplication by addition
10-7
Trace of Function multiply(6,3)
10-8
Terminating Condition
• The recursive functions always contains one or more terminating
conditions.
• A condition when a recursive function is processing a simple
case instead of processing recursion.
10-9
Types of Recursion
Direct Recursion Indirect Recursion
A function is said to be indirect recursive if
A function is said to be direct it calls another function and this new
recursive if it calls itself directly. function calls the first calling function
again.
int func1(int n)
{ if (n<=1)
int fibo (int n) return 1;
{ else
if (n==1 || n==2) return func2(n);
return 1; }
int func2(int n)
else
{
return (fibo(n-1)+fibo(n-2));
return func1(n);
}
}
Simple example
main()
{
printf(“This is an example of recursive function”);
main();
}
If you don't, the function will never return once you call it.
Program to find the sum of natural numbers using recursion
#include <stdio.h>
int sum(int n);
int main()
{ int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number); Enter a positive integer: 3
sum = 6
result = sum(number);
printf("sum = %d", result); return 0; }
int sum(int num)
{ if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num; }
Program to find GCD using recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{ int n1, n2;
printf("Enter two positive integers: "); Enter two positive
integers: 366 60
scanf("%d %d", &n1, &n2); G.C.D of 366 and 60 is 6.
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));
return 0; }
int hcf(int n1, int n2)
{ if (n2 != 0)
return hcf(n2, n1%n2);
else return n1;
}
Thank You......