C - SPLessons

Chapter 19

Recursion in C

Recursion in C

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.

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

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

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,

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

//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

Summary

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

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