UPI Study › Courses › Programming in C › Free lessons › Lesson 5.7 Free with a free account
Workshop: Summation, Factorial, and Input Validation
Programming in C · Chapter 5: Loop Constructs, Control Statements, and Error DiagnosisSection 5.7 · lesson 32 of 788 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: Function Definition in C →← Nested Loops and Common Loop ErrorsNext lesson: Function Definition in C →
In this lesson
Accumulating sums and products safely and rejecting bad input in C.
- Use an accumulator that starts at 0 for sums and 1 for products
- Check a loop's result against a formula to catch off-by-one errors
- Test for overflow before multiplying, using ULLONG_MAX from limits.h
- Validate numeric input with scanf's return value and getchar
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 (1,126 words). Read along, or search it.
Workshop Plan
Three Closing-Time Jobs
At the end of every night, the Starlight Arcade's counter has three jobs. Add up all the tokens. Make sure the display doesn't overflow. And check that nobody typed a silly number. In this workshop, you'll build three small programs for those jobs, one step at a time. One adds things up, one multiplies things up, and one refuses bad answers until a good one arrives.
Accumulator
Summing 1 to n With a Formula Check
Program one: adding things up. An accumulator is a variable that starts at a known value, and collects a little more on each pass. For a sum, it starts at zero, because adding nothing gives zero. First version: add the numbers one up to n. You know how many passes, so it's a for loop. Each pass adds its own number to sum. Build it, run it, and type ten. Fifty-five. The last line is a check. Math class says the sum of one to n is n times n plus one, over two. That's fifty-five for ten, and the loop agrees. A second way to get the answer is a great test. Change the test to i less than n, the off-by-one from five point six, and run it again. Forty-five, while the formula line still says fifty-five. The mismatch catches the bug at once.
Sentinel Sum
Averaging Scores Until Minus One
Second version: add up scores until the player types minus one. Now you don't know how many passes, so it's a while loop. Minus one is a sentinel: a value that means no more, and can never be a real score. Read once before the loop, and again at the bottom of the body. Build it, run it, and type eighty, ninety-five, seventy, eighty-five, and then minus one, all on one line. Four scores, a total of three hundred thirty, and an average of eighty-two point five. Two details matter. First, the guard: count equals zero. Typing minus one straight away leaves count at zero, and dividing by zero is a bug. Second, the cast to double makes the division give eighty-two point five, not eighty-two.
Quick Check
A Sentinel in the Middle of a Line
Quick check. Sam, who tests the arcade's programs, runs it and types fifty, minus one, and seventy, on one line. What does it report? Pause and predict. One score, a total of fifty, and an average of fifty point zero. The first read gets fifty, and the loop adds it. The next read gets minus one, the sentinel, so the loop stops right there. The seventy is never read at all. A sentinel ends the input, even in the middle of a line.
Running Product
Factorial With an Overflow Check
Program two: multiplying things up. The factorial of n, written n with an exclamation mark, is one times two times three, and so on, up to n. So five factorial is a hundred twenty. It's a running product, so the accumulator starts at one, not zero. Multiplying by zero would wipe out every pass. Factorials grow fast. A variable holds only so many digits, and past that it overflows: the answer no longer fits. The biggest unsigned long long is about eighteen point four quintillion. That's typical: eight bytes, as in two point four. The safe way is to ask before multiplying: if I multiply fact by i, will it still fit? That's true exactly when fact is no bigger than U L long max, divided by i. U L long max is a constant from limits dot h. When the test fails, the program leaves with break, from five point five. Build it, run it, and ask for twenty-two factorial. Every fifth step prints. Twenty factorial fits. But twenty-one doesn't, so the loop stops before multiplying. Twenty factorial is bigger than U L long max divided by twenty-one. And percent L L U is how printf shows an unsigned long long.
Overflow
Unsigned Numbers Wrap Around Quietly
What if there were no check? Unsigned numbers don't crash. They wrap around to the start, like an odometer rolling over, and keep going quietly. Here's the same product with no test, run up to twenty-one. Build and run it. It prints a big number, with no warning at all. The right answer is about fifty-one quintillion. This is what's left after wrapping past the top. A quiet wrong answer is worse than a loud error. And for signed types like int, overflow is undefined behavior: never rely on what it does. So test first, then multiply. Checking after multiplying is too late: the wrong value is already stored.
Input Validation
Checking What scanf Returns
Program three: asking until the answer is good. The arcade kiosk sells one to a hundred tokens, and people type letters, negative numbers, and huge numbers. The program refuses politely, and asks again. A flag named valid starts at zero, and becomes one only for a good answer. The key is scanf's return value: how many items it read. One percent d, read successfully, returns one. Letters give zero. And E O F means the input has ended. Letters stay in the input. So when scanf doesn't return one, a small loop throws away characters with getchar, up to the end of the line. Build it, run it, and type some answers. A b c is not a whole number. Minus five and two hundred fifty are out of range. Forty is accepted. Four tries: three refusals, and one success. Priya, who writes the arcade's programs, built her first kiosk without the getchar loop. Sam typed a b c, and the screen scrolled forever with the same question. Scanf failed on the same letters every time, because nothing ever removed them. The getchar loop is the fix.
Quick Check
The Word Ten, Zero, Then One Hundred
Quick check. Sam runs the kiosk again, and types the word ten, then zero, then one hundred. What's the last line it prints? Pause and predict. It buys one hundred tokens. Watch the run. The word ten is letters, so scanf returns zero: not a whole number, and the rest of the line is thrown away. Zero is a number, but it's below one, so it's refused. One hundred passes, because the test is greater than a hundred, not greater than or equal.
Challenges
Three Exercises to Try
Three challenges to try on your own. Work out each expected answer by hand first. Add only the odd numbers up to n, using continue for the even ones. Make the factorial print every pass, and find where it would stop for an int, using INT MAX. And let the kiosk give up after three bad tries, with a counter and break.
Key Takeaways
Sums, Products and Validation in Review
To sum up. An accumulator starts at zero for a sum, and at one for a product. Check a loop's answer a second way, like a formula, to catch an off-by-one. Test for overflow before multiplying: ask whether fact is above the maximum divided by i. And to validate input, check scanf's return value, and throw away a bad line with getchar.
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: Summation, Factorial, and Input Validation
What is an accumulator variable in C?
How do you prevent factorial overflow in C?
Why does unsigned integer overflow give a wrong answer without an error?
How do you check scanf's return value to validate input?
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 →