UPI Study › Courses › Programming in C › Free lessons › Lesson 6.7 Free with a free account
Workshop: Multi-Function Programs and Recursion
Programming in C · Chapter 6: Functions, Scope, Storage Classes, and RecursionSection 6.7 · lesson 39 of 787 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: One-Dimensional Arrays in C →← Recursion: Functions That Call ThemselvesNext lesson: One-Dimensional Arrays in C →
In this lesson
Splitting programs into one-job functions and tracing recursive calls.
- Split a program into small functions that each do one job
- Use an early return to stop on invalid input
- Count recursive calls with a file-level counter
- Debug a recursive function with a trace of each call
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 (966 words). Read along, or search it.
Workshop Plan
Building in Small Tested Pieces
A big program is never written in one go. Builders cut the job into small pieces, make sure each piece works, and only then join them. In this workshop, you'll build three programs for the Starlight Arcade that way. An arcade score tool split into functions, a recursive power and Fibonacci counter, and a palindrome check that explains itself.
Planning
Read, Check, Compute and Print
Program one turns a game score into prize tickets: one for every 100 points, plus 5 bonus tickets at 900 or more. Scores run from 0 to 1000. Priya splits the job into four small functions, each with one task: read, check, compute, and print. A function called play_round joins them, in that order. A function that does one thing is easy to test on its own. So build in that order too. Write read_score, and test it. Then add is_valid, and test a good number and a bad one. Then the rest.
Worked Example
A Score-to-Ticket Program
Here's the finished program. read_score prints a prompt, reads a number with scanf, and returns it. is_valid returns 1 when the score is from 0 to 1000, and 0 otherwise. The whole answer is one logical expression. tickets_for divides by 100, and adds the bonus at 900 or more. print_report only prints, so its return type is void. play_round reads a score and checks it. If the score is bad, it prints a message, and leaves early with a plain return. Build it, and run it with two players, who type 1250, then 930. Player one's score is above 1000, so is_valid returned 0, and play_round left early. Player two scored 930: 9 tickets, plus 5 bonus, makes 14.
Quick Check
Tickets for a Top Score
Quick check. Here are the checker and the ticket counter on their own, testing the top score, 1000. How many tickets does it print? Pause and predict. Build and run: 15 tickets. 1000 is valid, because the test is less than or equal to 1000. Then 1000 over 100 is 10, and a score of at least 900 adds 5. Testing the edge values is exactly why each piece stands alone.
Worked Example
Counting Power and Fibonacci Calls
Program two: two classic recursive jobs, and a counter to show what each one costs. Power of 2 and 10 means 2 times itself, 10 times. That's 2 times power of 2 and 9. The base case: anything to the 0 is 1. A Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8. So fib of n adds fib of one less, and fib of two less. A file-level variable, calls, goes up by one every time either function starts. That's file scope, from lesson 6.3. Run it. The power took 11 calls: one for each exponent from 10 down to 0. fib of 4 took 9 calls, and fib of 10 took 177. And fib of 20 needed 21891 calls, though its answer is only 6765. Each fib call makes two more calls, and they repeat each other's work. A loop would need only about 20 steps for the same answer.
Call Tree
Where Nine Fibonacci Calls Go
Here's where fib of 4's nine calls go. fib of 4 calls fib of 3 and fib of 2, and each of those calls two more, down to the base cases. fib of 2 is worked out twice, fib of 1 three times, and fib of 0 twice. Nine calls, for an answer of 3.
Worked Example
A Recursive Palindrome Check
Program three. A palindrome number reads the same forward and backward, like 1221. To test one, reverse its digits, and compare. Reversing is recursive. Peel the last digit off n, and tack it onto the end of a growing rev, with rev times 10 plus n percent 10. Then continue with n over 10. The base case is n equal to 0: no digits left, so rev is the answer. A trace line prints what the function receives on every call, and the variable debug switches it on or off. Build it, and type 1221. n shrinks while rev grows: 1, 12, 122, and finally 1221, the same as the input. Yes. For 1234, the trace ends at 4321, so the answer is no. When you're done, set debug to 0, so players never see the trace.
Debugging
A Trace Finds the Missing Times Ten
Sam's first checker said 1221 was not a palindrome. Here's his recursive line: rev plus n percent 10, with no times 10. Run it, and read the trace with Priya. The second call looks fine: rev is 1. But the third call shows rev 3, where the right code had 12. The digit was added on, not shifted left. That's the first call where the numbers go wrong. Put the times 10 back, and run again: it reads the same both ways. When a recursive function gives a wrong answer, a trace like this shows you the first call that stops matching your work on paper.
Quick Check
Reversing 560
Quick check. Here's the fixed reverse, with a shorter trace line. This time main tests 560. On the last trace line, what is rev? Pause and predict. Build and run. The last line shows rev 65, so 560 is not a palindrome. The trailing 0 was peeled off first, and 0 times 10 plus 0 is still 0. A whole number can't keep a leading zero, so rev ends at 65.
Challenges
Two Ideas to Try
Two ideas to try on your own. Make a score of 500 or more earn 2 extra tickets, by changing only tickets_for. And write a recursive count_digits. Its base case is a number below 10. Work out each answer by hand first, then run.
Key Takeaways
Multi-Function Programs in Review
To sum up. Give each function one job, and test each piece before you join them. Check input first, and leave early with return when it's bad. A file-level counter shows what a recursive function really costs. And a trace of each call's values points straight at the first wrong step.
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 Workshop: Multi-Function Programs and Recursion
Why should each C function do only one job?
Why is recursive Fibonacci so slow?
How do you check if a number is a palindrome with recursion in C?
How do you debug a recursive function that gives a wrong answer?
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 →