English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C Language Recursion

In this tutorial, you will learn how to write recursive functions in C programming language with the help of examples.

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();
    ... .. ...
}

Recursion continues until a certain condition is met to prevent recursion.

To prevent infinite recursion, a recursive call can be made in one branch while the other branch does not make a recursive call.if ... else statement(or similar methods).

Example: Using recursion to calculate the sum of natural numbers

#include <stdio.h>
int sum(int n);
int main() {
    int number, result;
    printf("Please enter a positive integer: ");
    scanf("%d", &number);
    result = sum(number);
    printf("sum = %d", result);
    return 0;
}
int sum(int n) {
    if (n != 0)
        //sum() function calls itself
        return n + sum(n-1); 
    else
        return n;
}

Output result

Please enter a positive integer:3
sum = 6

Initially, sum() is called from the main() function, and number is passed as an argument.

Assuming the initial value of n in sum() is3. During the next function call, the2Passed to the sum() function. This process continues until n equals 0.

When n equals 0, the if condition fails, and the else part is executed, finally returning the integer and sum to the main() function.

Advantages and disadvantages of recursion

Recursion makes the program elegant. However, if performance is crucial, use loops instead, because recursion is usually much slower.

Although so, recursion is an important concept. It is often used in data structures and algorithms. For example, recursion is usually used in problems such as tree traversal.