Workshop: Summation, Factorial, and Input Validation

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

← Nested Loops and Common Loop ErrorsNext lesson: Function Definition in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
An accumulator is a variable that starts at a known value and collects a little more on each loop pass. For a sum it starts at 0, and for a running product such as a factorial it starts at 1, because multiplying by 0 would wipe out every pass. Adding 1 through 10 gives 55, which matches the formula n(n + 1) / 2.
How do you prevent factorial overflow in C?
Check before multiplying: fact * i still fits in an unsigned long long exactly when fact <= ULLONG_MAX / i, using the constant from limits.h. If the test fails, leave the loop with break. With the usual 8-byte unsigned long long, 20! = 2,432,902,008,176,640,000 fits, but 21! does not. Checking after multiplying is too late, because the wrong value is already stored.
Why does unsigned integer overflow give a wrong answer without an error?
Unsigned arithmetic in C wraps around, like an odometer rolling over, so an overflowing product quietly becomes a smaller number. Multiplying up to 21! in an unsigned long long prints a large wrong value instead of about 51 quintillion, with no warning. Overflow of signed types such as int is different: it is undefined behavior, so code should never rely on what it does.
How do you check scanf's return value to validate input?
scanf returns how many items it read successfully, so a single %d returns 1 for a number, 0 for letters, and EOF when input has ended. When it does not return 1, the bad characters stay in the input, so discard them with getchar until a newline or EOF before asking again. Without that step, scanf fails on the same letters forever.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →