UPI Study › Courses › Programming in C › Free lessons › Lesson 6.6 Free with a free account
Recursion: Functions That Call Themselves
Programming in C · Chapter 6: Functions, Scope, Storage Classes, and RecursionSection 6.6 · lesson 38 of 786 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Workshop: Multi-Function Programs and Recursion →← Pass by Value vs. Pass by Reference in CNext lesson: Workshop: Multi-Function Programs and Recursion →
In this lesson
Writing C functions that solve a problem by calling themselves.
- Identify the base case and recursive case of a recursive function
- Trace recursive calls and returns on the call stack
- Write recursive factorial and digit-sum functions
- Compare recursion with an equivalent loop
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (855 words). Read along, or search it.
Opening Analogy
A Hall of Mirrors
Stand between two mirrors, and you see a hall of smaller and smaller copies of yourself, each one inside the last. A function can do something like that. It can call itself, to solve a smaller piece of the same job. It sounds like a trick that never ends. And it would never end, except for one small rule you'll learn here.
Two Required Parts
Base Case and Recursive Case
A function that calls itself is called recursive. Every recursive function needs exactly two parts. The base case: a situation so small that the answer is simple, so the function stops calling itself. And the recursive case: a call to itself with a smaller problem, one step closer to the base case. Think of a rocket countdown. If the count is 0, say Liftoff, and stop. Otherwise, say the number, then count down from one less. Run it with 3. Three, two, one, Liftoff! A countdown that uses a smaller countdown.
Worked Example
Factorial Through Stacked Calls
The factorial of a number multiplies every whole number from 1 up to it. 4 factorial is 4 times 3 times 2 times 1, which is 24. Notice that 4 factorial is just 4 times 3 factorial. Each factorial hides a smaller one inside it. The base case is 1 factorial, which is 1. So fact returns 1 when n is at most 1. Otherwise, it returns n times fact of one less than n. Two printf lines show the work. Run it. The calls start, each stepping into the next: four, three, two, one. Every call gets its own frame on the call stack, holding its own n. The pile grows until the base case. Then fact of 1 returns first, and the answers flow back down: 1, then 2, then 6, then 24. The last call to start is the first to finish. And nothing was multiplied until the base case answered. What about fact of 0? Mathematicians define 0 factorial as 1, and the test n at most 1 catches 0 too.
Worked Example
Summing a Number's Digits
Recursion isn't only for multiplying. Take the sum of a number's digits: 4821 gives 4 plus 8 plus 2 plus 1, which is 15. Two tricks from lesson 2.5 do the work. n percent 10 is the last digit, and n divided by 10 chops that digit off. The base case is a one-digit number, which is its own digit sum. So the answer is the last digit, plus the digit sum of the rest. Run it: 15. Each call hands the next a number one digit shorter, and the sums add up on the way back.
Common Mistake
Runaway Recursion and Stack Overflow
Now forget the base case. This countdown never stops calling itself. Every call adds a frame to the stack, and the stack has a fixed size. It runs out of room: a stack overflow, and the operating system stops the program. Clang catches this obvious case. Build it, and it warns: all paths through this function will call itself. But it can't catch every runaway. Add a base case, and make the call move away from it, with n plus one. The build is silent. Starting at 3, the count never reaches 0. So ask before every run: does each call get closer to the base case?
Comparison
Recursion Versus a Loop
Any recursive function can also be written with a loop. Here's factorial both ways: recursion on the left, a for loop on the right. Run both with 5. Each prints 120. A loop uses one frame, and reuses its variables, so it's lighter. A recursive function makes a frame for every call, which costs memory and time. A loop fails by never reaching a false condition, and keeps running. Recursion fails by never reaching its base case, and overflows the stack. Recursion wins when a problem is naturally made of smaller copies of itself, and the code gets shorter and clearer.
Quick Check
Printing After the Recursive Call
Quick check. This function looks like the countdown, but two of its lines have traded places. Main calls show of 3. What does it print? Pause and predict. Build and run: one, two, three. Show of 3 calls show of 2 before it prints anything, and show of 2 calls show of 1. Show of 0 returns at once. Then each waiting frame finishes its printf on the way back: 1, then 2, then 3. Work done after the recursive call happens in reverse order, just like the returns of fact.
Quick Check
The Digit Sum of 305
One more, back to digit sum. This time main asks for the digit sum of 305. What does it return? Pause and predict. Build and run: eight. 305 gives 5, plus the digit sum of 30. 30 gives 0, plus the digit sum of 3. And 3 is a base case. So it's 5 plus 0 plus 3: eight. The zero in the middle still costs one call.
Key Takeaways
Recursion in Review
To sum up. A base case stops the calls, and the recursive case makes the problem smaller. Each call gets its own frame on the stack, with its own variables. The last call to start is the first to return, so answers come back in reverse order. And with no base case reached, the stack overflows. A loop is often the lighter choice.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Recursion: Functions That Call Themselves
What are the base case and recursive case in recursion?
How does a recursive factorial function work in C?
What causes a stack overflow in a recursive function?
Is recursion or a loop better in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →