C Language | Functions | Recursion

This article explains recursion, in which a function calls itself.

Functions That Call Themselves

Previous articles explained how one function calls another. What happens if a function calls itself? Calling a function from within itself is called recursion. Consider the following function.

void Function() {
 Function();
}

The Function() function calls itself. Because it continues calling itself forever, it enters an infinite loop.

Recursion can create specialized loops. However, most recursive operations can also be implemented with iteration statements. Recursion is uncommon because function calls are slower than loops created with iteration statements. Its advantage is that it can simplify certain algorithms.

Code 1

#include <stdio.h>

void Function(int , int);

int main() {
 Function(0 , 10);
 return 0;
}

void Function(int iCount , int iMax) {
  if (iCount < iMax) {
    printf("Count = %d\n" , iCount);
   Function(iCount + 1 , iMax);
  }
}

Code 1 is a simple program that demonstrates recursion. The recursive Function() function receives the initial counter value as its first argument and the maximum value as its second argument. While iCount is less than iMax, Function() increments the counter and calls itself with Function(iCount + 1, iMax).

As this repeats, iCount eventually reaches iMax. Each invocation of Function() then returns control in reverse order until execution returns to the original caller. Another recursive technique is mutual recursion, where function A() calls function B() and function B() calls function A().

void FunctionA() {
 FunctionB();
}

void FunctionB() {
 FunctionA();
}

Recursion is not used often in ordinary programs, but it is useful for tasks such as analyzing and searching tree-structured data.