C - SPLessons
boy2 Chapter 19

Recursion in C

C - SPLessons

Recursion in C

shape Description

Recursion in C can be defined as the process of calling a function itself repeatedly. The function is called as “Recursive function“. This is similar to looping concept which repeats the same code discussed earlier.

Recursion in C helps in expressing ideas in which the recursive call result, necessary to complete the task. Sometimes the process may complete without the recursive call also.

shape Syntax

void recursive_function()
{
//statements;
recursive_function();
}
int main()
{
//statements;
recursive_function();
}

shape Conceptual
figure

What happens if Recursion in C continues for many times..?

shape Reason

Basic function of Recursion in C is to repeat many times and it may happen forever.But, in real time what happens is,after some recursions, the program gets crashed. This is because,

shape Example - 1

Control flow for factorial example will be as follows.

//program for finding factorial of a number
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fact(int);
int main()
{
	int number,f;
	printf("\nEnter a number: ");
	scanf("%d",&number);
	f=fact(number);
	printf("\nFactorial of %d is: %d",number,f);
	return 0;
}
int fact(int n)
{
	if(n==1)
	{
		return 1;
	}
	else
		return(n*fact(n-1));
}

Output:


Enter a number: 5

Factorial of 5 is: 120

shape Example - 2

//program for finding sum of n numbers
#include<stdio.h>
#include<math.h>
int main()
{
	int a,sum;
	printf("Enter the value of n: ");
	scanf("%d",&a);
	sum = getSum(a);
	printf("Sum of n numbers: %d",sum);
	return 0;
}

int getSum(a)
{
	static int sum=0;
	if(a>0)
	{
		sum = sum + a;
		getSum(a-1);
	}
	return sum;
}

Output:

Enter the value of n: 8
Sum of n numbers: 36

shape Advantages

shape Disadvantage

Summary

shape Key Points

  • Recursive function calls itself for multiple times.
  • Stacks are created during recursion.

shape Programming
Tips

Take care of count of Recursion in C because it leads to overflow.