Last chapter ended with a bill for one customer: one number in, one bill out. Now picture the billing office on meter-reading day. There are thousands of customers, and the program must do the same few steps for every one of them. Nobody writes the same twenty lines five thousand times, and nobody wants to edit the program next month when the number of customers changes. A class is the same. A teacher has the marks of sixty students and wants the total and the average. Typing scanf sixty times is silly, and the day the class grows to sixty-two you would have to change the program. So you tell the computer once: do this, again and again, until I say stop. That is a loop, and it is the third power of a program, after calculating and choosing: repeating.
Until now every line ran at most once. Now a few lines will run many times, and the interesting questions change. How many times? What do the variables hold when it stops? When does it never stop at all? Those are exactly the questions exam papers ask.
By the end of this chapter you'll be able to write all three of C's loops, for, while and do-while, and say which one a job needs. You'll work out, without running anything, how many times a loop runs and what its counter holds afterwards. You'll recognise the traps: a stray semicolon, a counter that jumps over its target, a loop that never ends. You'll steer a loop with break, continue and goto, print tables and patterns with loops inside loops, and write the loop programs written papers ask for: the sum of 1 to 100, the average of some of the inputs, the largest of several numbers, a factorial.
We'll go in five parts: the three loops; steering them with break, continue and goto; counting passes and the traps; loops inside loops; and programs that add, count and search. Every program here was compiled and run, and the output you see is the real output.