14. How Can I Do the Same Stuff Over and Over?

With while and do-while Loops

image

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 and 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 the 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:

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.

Clue

image

The body of the while repeats as long as the condition is true. Remember how the if works: 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 lots 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 the braces will still be there if you add statements to the while later. Never put a semicolon after the while’s parenthesis. The semicolon follows only the statements inside the body of the while.

Figure 14.1. The if body executes once, and the while body can repeat more than once.

image

Warning

image

The two statements in Figure 14.1 are similar, but they don’t do the same thing. while and if are two separate statements that do two separate things.

You must somehow change a variable inside the while loop’s condition. If you don’t, the while will loop forever because it will test the same condition each time through the loop. Therefore, you avoid infinite loops by making sure the body of the while loop changes something in the condition so that eventually the condition will become false and the program will continue with the statements that follow the while loop.

Note

image

As with if, the while might never execute! If the condition is false going into while the first time, the body of the while doesn’t execute.

Using while

If you want to repeat a section of code until a certain condition becomes false, while is the way to go. The Blackjack program in Appendix B contains a slick use of while in the dispTitle() function to clear the screen. The function is repeated here for your review:

image

Warning

image

Almost every C compiler has a built-in function that clears the screen. The problem is that none of these screen-clearing functions are compatible with the ANSI C standard. Therefore, I used another method to erase the screen before each Blackjack game. A while loop prints 25 newlines. When the cursor gets to the bottom of a screen, the screen scrolls upward, and what was on the screen gets pushed off the top. This simple and generic screen-clearing function, written using while, works with all ANSI C compilers, such as the one you probably have.

Note

image

The looping method for screen clearing is not really elegant, but it’s about the most generic way possible to clear the screen. If you want to dig through your compiler’s manual and replace this while loop with your compiler’s screen-clearing function, go ahead.

Back to the actual while code needed to clear the screen: The variable i is initially set to 0. The first time while executes, i is less than 25, so the while condition is true and the body of the while executes. In the body, a newline is sent to the screen and i is incremented. The second time the condition is tested, i has a value of 1, but 1 is still less than 25, so the body executes again. The body continues to execute until i is incremented to 25. Because 25 is not less than 25 (they are equal), the condition becomes false and the loop stops repeating. The rest of the program is then free to execute.

Clue

image

If i were not incremented in this screen-clearing while, the printf() would execute forever or until you pressed Ctrl+Break to stop it.

Using do-while

while also can be used in conjunction with the do statement. When used as a pair, the statements normally are called do-while statements or the do-while loop. The do-while behaves almost exactly like the while loop. Here is the format of do-while:

image

Use a do-while in place of a while only when the body of the loop must execute at least one time. The condition is located at the bottom of the do-while loop, so C can’t test the condition until the loop finishes the first time.

The Blackjack program asks the user to type an H or an S—in other words to hit (that’s casino lingo for drawing another card) or stand. However, users don’t always type what they’re supposed to. Therefore, when you request user input that has a fixed number of possibilities, such as an H or an S, you should check what the user enters to make sure it’s one of the answers you’re expecting. Here is a sample do-while, similar to that used in the Blackjack program, that keeps asking the user for an answer until the user gets it right:

image

The strange-looking getAns() function call simply executes a function that displays the Hit or stand (H/S)? message and gets a character from the user into ans. For now, study the formation of the do-while because that is the center of your concern here.

Clue

image

Chapter 19, “Can You Tell Me More About Strings?,” explains how to test for an uppercase Y or N or a lowercase y or n with a built-in function named toupper().

Rewards

image

• Use while or do-while when you need to repeat a section of code.

• Make sure that the body of the while or do-while loop changes something in the condition, or the loop will repeat forever.

• Remember that loops differ from if because the body of an if executes only once instead of lots of times if the condition is true.

Pitfalls

image

• Don’t put a semicolon after the while condition’s closing parenthesis. If you do, an infinite loop will occur.

• Don’t assume that the user will answer questions the way you expect. Keep asking for an answer until the user types what you need.

In Review

The goal of this chapter was to show you how to repeat sections of code. The while and do-while loops both repeat statements within their statement bodies. All code between the while and do-while braces repeats instead of executing only once. Both the while and do-while statements cause their code sections to repeat while a given relational condition is true.

The difference between the two statements lies in the placement of the relational test that controls the loops. The while statement tests the relation at the top of the loop, and the do-while statement tests the relation at the bottom of the loop, forcing all its statements to execute at least once.

Code Example

image

Code Analysis

The code shows both kinds of loops presented in this chapter. The program prints the numbers from 1 to 20 twice. The first half of the program uses while to control the loop, and the second half uses do-while to control the loop. As you can see, both kinds of loops can do the very same thing. The choice of while and do-while is often trivial. You would choose one over the other only when the first cycle was important and you wanted the loop to execute at least once (with do-while), or maybe not at all.

By the way, if the printf() functions included ctr’s increment like this:

{ printf("%d ", ctr++); }

you would not need the increment statements that appear on lines by themselves. The separate increments, however, make the program a little easier to read, and readability is more important that extreme efficiency in most cases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.36.30