100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Recursion in C

Master recursion in C: base case, recursive case, call-stack tracing, factorial example, and avoiding stack overflow.

Functions & RecursionBeginner15 min readJul 7, 2026
Analogies

1. Introduction

Recursion is a technique in which a function calls itself, directly or indirectly, to solve a problem by breaking it down into smaller instances of the same problem. In C, any function can call itself as long as it eventually reaches a stopping condition. Recursive solutions are common for problems with a naturally repetitive, self-similar structure, such as computing factorials, Fibonacci numbers, traversing tree-like data structures, and implementing divide-and-conquer algorithms like merge sort and quick sort.

🏏

Cricket analogy: Recursion is like a coach breaking down "how India won the 2011 World Cup" into "how they won the semifinal" plus "how they won one final match," repeating until reaching the simplest case of a single ball bowled — used for tree-like problems like tournament bracket analysis.

Every recursive function must have two essential parts: a base case, which is the simplest instance of the problem that can be answered directly without further recursion, and a recursive case, which breaks the problem into a smaller sub-problem and calls the function again to solve it. Without a correctly reached base case, a recursive function calls itself indefinitely, eventually exhausting the program's memory.

🏏

Cricket analogy: The base case is like reaching the final ball of a Super Over that ends the match outright with no more play needed, and the recursive case is like each earlier over setting up the next one; skip the base case and you get a match that never ends, exhausting the stadium's time slot.

2. Syntax

c
returnType functionName(parameters) {
    if (baseCondition) {
        return baseResult;      /* base case: stops recursion */
    } else {
        return someExpression(functionName(smallerProblem));  /* recursive case */
    }
}

The recursive case must always move the problem closer to the base case (for example, by decreasing a number, shrinking an array bound, or moving toward an empty list); otherwise the recursion never terminates.

🏏

Cricket analogy: Just as a batsman's run count toward a century must strictly increase with every scoring shot to eventually reach 100, each recursive call must shrink the problem — like reducing overs remaining — toward the base case, or the "innings" of recursion never ends.

3. Explanation

3.1 Base Case and Recursive Case

Consider factorial: n! = n * (n-1)! for n > 0, and 0! = 1 by definition. Here, 0! = 1 is the base case (it needs no further recursive call), and n! = n * factorial(n-1) is the recursive case. Every recursive call must work on a smaller version of the original problem (n-1 instead of n) so the sequence of calls eventually reaches the base case rather than continuing forever.

🏏

Cricket analogy: Computing a batting milestone like "runs needed for a century" works like factorial: reaching 0 runs needed is the base case (century already scored), while needing n runs equals scoring 1 run plus needing n-1 more, each ball working toward the smaller remaining target.

3.2 How the Call Stack Works

Each time a function calls itself, the C runtime pushes a new stack frame onto the call stack. A stack frame stores that call's local variables, parameters, and the return address (where execution should resume once this call finishes). These frames pile up as recursive calls go deeper ('winding up'), and then, once the base case is reached, each frame is popped off the stack in reverse order as the calls return and their pending arithmetic completes ('unwinding'). This is why recursive functions can perform work both before the recursive call (going down) and after it (coming back up), by using the returned value.

🏏

Cricket analogy: Each recursive call is like a fielding substitution slip stacked on the umpire's clipboard, storing which player and position to restore; as substitutions wind up during a rain delay, they pile up, then unwind in reverse order as play resumes, restoring each fielder in turn.

3.3 Step-by-Step Trace: factorial(4)

Winding phase (calls pushed onto the stack, each waiting for the next call's result): factorial(4) calls factorial(3); factorial(3) calls factorial(2); factorial(2) calls factorial(1); factorial(1) calls factorial(0). factorial(0) is the base case and returns 1 immediately without calling itself again.

🏏

Cricket analogy: Tracing a winding call chain like reviewing "over 4" requires reviewing "over 3," which requires "over 2," then "over 1," then "over 0"; over 0, the base case, is simply the coin toss with no prior over to check, returning immediately.

text
Call stack grows (winding):
factorial(4)
  -> factorial(3)
       -> factorial(2)
            -> factorial(1)
                 -> factorial(0)  returns 1   [base case]

Call stack shrinks (unwinding), each frame multiplies by n:
factorial(1) = 1 * factorial(0) = 1 * 1   = 1
factorial(2) = 2 * factorial(1) = 2 * 1   = 2
factorial(3) = 3 * factorial(2) = 3 * 2   = 6
factorial(4) = 4 * factorial(3) = 4 * 6   = 24

Final result: factorial(4) = 24

Notice that no multiplication happens until factorial(0) returns 1; only then does each pending frame perform its multiplication as control unwinds back up to factorial(4), producing the final answer 24.

🏏

Cricket analogy: No runs are tallied until the base over(0) confirms "no more balls," and only then does each pending over's score get added back up the chain during the unwind, producing the final match total, like the total 24 runs.

3.4 Stack Overflow Risk

The call stack has a limited, fixed size determined by the operating system and compiler settings. Every recursive call consumes additional stack memory for its frame. If a recursive function never reaches its base case (due to a missing or incorrect base condition, or an argument that never converges toward it), the stack keeps growing until it exceeds this limit, causing a stack overflow — typically crashing the program with a segmentation fault rather than raising a catchable C error.

🏏

Cricket analogy: The call stack is like a stadium's fixed seating capacity for substitute players on the bench; if a match keeps calling up substitutes without a proper "final sub" base case, the bench overflows past capacity, causing a chaotic abandonment rather than a clean rule-based stoppage.

A missing or unreachable base case is the most dangerous recursion bug. For example, int factorial(int n) { return n * factorial(n - 1); } has NO base case at all — it will recurse forever (or until n underflows into negative numbers and the program crashes with a stack overflow). Always verify that (1) a base case exists, and (2) every recursive call moves strictly toward it, before trusting a recursive function with real input.

Tip: When designing a recursive function, write the base case FIRST and verify it independently, then write the recursive case assuming smaller sub-problems already work correctly (this is called the 'recursive leap of faith'). For performance-sensitive code operating on large inputs, also consider whether an iterative (loop-based) version would avoid the stack-depth and function-call overhead that recursion introduces.

4. Example

c
#include <stdio.h>

/* Recursive factorial: n! */
long factorial(int n) {
    if (n == 0) {          /* base case */
        return 1;
    }
    return n * factorial(n - 1);   /* recursive case */
}

/* Recursive Fibonacci: nth term (0-indexed: 0, 1, 1, 2, 3, 5, ...) */
int fibonacci(int n) {
    if (n == 0) return 0;   /* base case 1 */
    if (n == 1) return 1;   /* base case 2 */
    return fibonacci(n - 1) + fibonacci(n - 2);   /* recursive case */
}

int main(void) {
    int num = 4;
    printf("factorial(%d) = %ld\n", num, factorial(num));

    for (int i = 0; i <= 6; i++) {
        printf("fibonacci(%d) = %d\n", i, fibonacci(i));
    }

    return 0;
}

5. Output

text
factorial(4) = 24
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(2) = 1
fibonacci(3) = 2
fibonacci(4) = 3
fibonacci(5) = 5
fibonacci(6) = 8

6. Key Takeaways

  • Every recursive function needs a base case (stops recursion) and a recursive case (reduces the problem and calls itself again).
  • Each recursive call pushes a new stack frame holding its own local variables and parameters onto the call stack.
  • Recursion has two phases: winding (calls stack up toward the base case) and unwinding (results combine as calls return).
  • In factorial(4), the base case factorial(0)=1 is reached first, then multiplications happen while the stack unwinds: 1*1=1, 2*1=2, 3*2=6, 4*6=24.
  • A missing or unreachable base case causes unbounded recursive calls, exhausting the stack and crashing with a stack overflow.
  • Fibonacci with two base cases (n=0 and n=1) demonstrates that a recursive case can call itself more than once per invocation.
  • Deeply recursive problems can often be rewritten iteratively with a loop to avoid stack-depth limits and call overhead.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#RecursionInC#Recursion#Syntax#Explanation#Base#Algorithms#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse