शब्दकोश · प्रोग्रामिंग

Recursion

Recursion is a technique where a function solves a problem by calling itself on smaller versions of that problem until it reaches a simple base case.

अपडेट: अक्टूबर 6, 2026

Recursion is when a function calls itself to solve a smaller instance of the same problem. Every correct recursive function has a base case that stops the calls and a recursive case that moves toward it.

Why it matters

Recursion is a natural fit for problems with nested or self-similar structure, such as walking a folder tree, parsing nested JSON or traversing a binary tree. The code is often shorter than the loop equivalent. The cost is that each call uses stack memory, so very deep recursion can fail.

Example

def factorial(n):
    if n <= 1:          # base case
        return 1
    return n * factorial(n - 1)   # recursive case

factorial(4) becomes 4 * factorial(3), then 3 * factorial(2), down to factorial(1) which returns 1, and the results multiply back up to 24.

Common mistakes

  • Omitting the base case or never moving toward it, which causes infinite recursion and a stack overflow error.
  • Recursing thousands of levels deep in languages that do not optimize tail calls; use a loop instead.
  • Recomputing the same sub-problem repeatedly, as in naive Fibonacci; cache results.

Get notified when this term updates

Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.

यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.