C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

14. Code Repeat—Using Loops to Save Time and Effort


In This Chapter


  • Saving time by looping through code

  • Using while

  • Using do...while


Now that you’ve learned the operators, you’re ready to play “loop the loop” with your programs. A
loop is simply a section of code that repeats a few times. You don’t want a loop to repeat forever—
that’s called an infinite loop. The loops you write (if you write them properly—and, of course, you
will) should come to a conclusion when they finish doing the job you set them up to do.


Why would you want a program to loop? The answer becomes clear when you think about the
advantage of using a computer for tasks that people wouldn’t want to do. Computers never get bored,
so you should give them mundane and repetitive tasks; leave the tasks that require thought to people.
You wouldn’t want to pay someone to add a list of hundreds of payroll figures, and few people would
want to do it anyway. Computer programs can do that kind of repetitive work. People can then
analyze the results when the computer loop finishes calculating all the figures.


If you want to add a list of figures, print company sales totals for the past 12 months, or add up the
number of students who enroll in a computer class, you need to use a loop. This chapter explains two
common C loops that use the while command.


while We Repeat


The while statement always appears at the beginning or end of a loop. The easiest type of loop that
uses while is called the while loop. (The other is called the do...while loop. You’ll see it a
little later.) Here is the format of while:


Click here to view code image


while (condition)
{ block of one or more C statements; }

The condition is a relational test that is exactly like the relational test condition you learned
for if. The block of one or more C statements is called the body of the while.


The body of the while repeats as long as the condition is true. This is the difference between a
while statement and an if statement: The body of the if executes if the condition is true. The
body of the if executes only once, however, whereas the body of the while can execute a lot of
times.


Figure 14.1 helps explain the similarities and differences between if and while. The formats of the
two commands are similar, in that braces are required if the body of the while has more than one
statement. Even if the body of the while contains only a single statement, you should enclose the
body in braces so that the braces will still be there if you later add statements to the while. Never
put a semicolon after the while’s parenthesis. The semicolon follows only the statements inside the

Free download pdf