Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Recursion

Recursion

Recursion is a method where a function calls itself, simplifying intricate problems into more manageable ones for resolution.

Understanding recursion can be challenging initially. The most effective approach to comprehend its mechanics is through experimentation.

Recursion Example

While adding two numbers is straightforward, summing a range of numbers presents a more intricate challenge. In the ensuing example, recursion is employed to accomplish this task by decomposing it into the simpler task of adding two numbers together recursively.

Example

int sum(int k);

int main() {
  int result = sum(10);
  printf(“%d”, result);
  return 0;
}

int sum(int k) {
  if (k > 0) {
    return k + sum(k – 1);
  } else {
    return 0;
  }

Example Explained

Upon invoking the sum() function, it adds the parameter k to the sum of all numbers less than k and yields the resultant sum. When k reaches 0, the function returns 0. During execution, the program progresses through the following steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )

10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

As the function doesn’t call itself when k equals 0, the program halts at that point and yields the result.

Developers should exercise caution with recursion, as it’s easy to create functions that never terminate or consume excessive memory and CPU resources. However, when implemented correctly, recursion can be an efficient and elegant solution to many problems.