C Programming Recursion

C Programming Recursion

C Programming Recursion

In this chapter you will learn how to create recursion functions in C programming.

Table of Contents

C Programming Recursion

A function that calls itself is called a recursive function and this technique is called recursion.

How does recursion work?

				
					void recurse()
{
    ... .. ...
    recurse();
    ... .. ...
}

int main()
{
    ... .. ...
    recurse();
    ... .. ...

				
			

The recursion continues until some condition is encountered that causes a bottleneck.

To prevent infinite recursion an if…else statement or some other such statement can be used where one part is recursive, but other parts are not.

Example: Recursion Function

				
					//Program for adding natural numbers using recursion
#include <stdio.h>
int sum(int num);

int main()
{
 int number, result;

 printf("Enter a positive integer: ");
 scanf("%d", &number);

 result = sum(number);

 printf("sum=%d", result);
}

int sum(int num)
{
 if (num !=0)
 // The sum() function calls itself
 return num + sum(num-1);
 else
 return num;
}
				
			

output

				
					Enter a positive integer: 3
sum= 6
				
			

In the above program the number variable sum() us passed as an argument to the function and the function is initially called main() from the function. sum()

Suppose initial value of num is 3. sum() 2 is passed through the function on the next function call. This process continues until the value of num is equal to 0.

When the value of num is equal to 0 the if condition fails and the else part executes and main() returns to the sum function.

Advantage adn Disadvantages of Recursion

Recursion keeps the program simple and transparent. All algorithms can be defined recursively using recursion. This makes it both easier to understand and to prove.

If speed is the main concern of your program, it is better not to use recursion. Because recursion takes up a lot of money and is generally slow. You can use for loop instead.

Leave a Comment

Your email address will not be published. Required fields are marked *