Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 17

C You in a While Loop

In This Chapter

Using a while loop

Choosing between for and while

Making infinite while loops

Beating a dead horse

When it comes time to create a loop, the C language gives you a choice. You can go with the complex for loop, which has all the gizmos and

options to make most programmers happy, or you can choose the more exotic, free-wheeling while loop for your programs. Whereas for is more official and lays out all its plans in one spot, while is fanciful and free — like those care­ free days of youth when Mommy would kiss your boo-boos and make them better and Daddy paid for everything.

This chapter introduces you to the happy-go-lucky while loop. Looping is a concept you should already be familiar with if you have been toiling with for loops for the past few chapters. But, I have good news! while loops are a heck of a lot simpler to understand. Ha-ha! Now, I tell you. . . .

The Lowdown on while Loops

While loops shouldn’t be strange to you. Consider the following:

While the light is red, keep your foot on the brake.

This simple example shows a while loop in real life. It means, roughly, “While this thing is true, keep repeating this action” (that is, a loop). Your foot is stepping on the brake as long as the light is red — a loop. Easy enough.

216 Part III: Giving Your Programs the Ability to Run Amok

If you want to rewrite this instruction by using a C-like syntax and a while loop, it could look like this:

while(light==RED)

{

foot_on_brake(); light = check_light();

}

light==RED is a condition that can be either TRUE or FALSE — as in an if statement. While that condition is TRUE, the statements held in the while loop’s curly braces are repeated.

One of the statements in the while loop checks the condition the loop repeats on: light=check_light() updates the status of the light variable. When it changes to something not RED, the while statement becomes FALSE, the block of statements is skipped, and the next part of the program is run. This is the essence of a while loop in C.

Whiling away the hours

As in a for loop, you can set up a while loop to repeat a chunk of statements a given number of times. Unlike a for loop, the while loop’s controls (the doo­ jabbies that tell the loop when to start and where to finish) are blasted all over the place. This is good because it doesn’t mean that everything is crammed into one line, as with a for loop. This is bad because, well, I get into that in the next section. For now, busy yourself by typing the source code for HEY.C, a bril­ liant C program shown right next:

#include <stdio.h>

int main()

{

int i;

i=1;

while(i<6)

{

printf(“Ouch! Please stop!\n”); i++;

}

return(0);

}

Chapter 17: C You in a While Loop 217

Type this program, which is essentially an update of the OUCH.C program, from Chapter 15. Both programs do the same thing, in fact, but by using dif­ ferent types of loops. Save the file to disk as HEY.C.

Compile. Run.

Here’s what the output looks like:

Ouch! Please stop!

Ouch! Please stop!

Ouch! Please stop!

Ouch! Please stop!

Ouch! Please stop!

Brilliant. Simply brilliant.

A loop in the C language requires three things: a start, a middle part (the part that is repeated), and an end. This information is from Chapter 15.

With a for loop, the looping-control information is found right in the for command’s parentheses.

With a while loop, the looping-control information is found before the loop, in the while command’s parentheses, and inside the while loop itself.

In HEY.C, the variable i is set up (or initialized) before the loop. Then, it’s incremented inside the loop. The while statement itself cares only when i is less than 6.

The statements belonging to the while — those lines clutched by the curly braces — are repeated only as long as the condition in parentheses is TRUE. If the condition is FALSE (suppose that the variable i was already greater than 6), those statements are skipped (as in an if statement).

While loops are easy targets for the infinite-loop boo-boo. For this reason, you have to check extra hard to make sure that the condition that while tests for eventually becomes FALSE, which makes the loop stop repeating.

For a while loop to quit, something must happen inside the loop that changes the condition that while examines.

This is probably the first time you have seen two different programs tackle the same problem: OUCH.C uses a for loop, and HEY.C uses a while loop. Neither one is better than the other. See the section “Deciding between a while loop and a for loop,” later in this chapter, for more information.

218 Part III: Giving Your Programs the Ability to Run Amok

The while keyword

(a formal introduction)

The while keyword is used in the C language to repeat a block of statements. Unlike the for loop, while only tells the computer when to end the loop. The loop must be set up before the while keyword, and when it’s looping, the ending condition — the sizzling fuse or ticking timer — must be working. Then, the loop goes on, la-de-da, until the condition that while monitors suddenly becomes FALSE. Then, the party’s over, and the program goes on, sadder but content with the fact that it was repeating itself for a while (sic).

Here’s the rough format:

starting; while(while_true)

{

statement(s); do_this;

}

First, the loop must be set up, which is done with the starting statement. For example, this statement (or a group of statements) may declare a variable to be a certain value, to wait for a keystroke, or to do any number of interesting things.

while_true is a condition that while examines. If the condition is TRUE, the statements enclosed in curly braces are repeated. while examines that condi­ tion after each loop is repeated, and only when the statement is FALSE does the loop stop.

Inside the curly braces are statements repeated by the while loop. One of those statements, do_this, is required in order to control the loop. The do_this part needs to modify the while_true condition somehow so that the loop eventually stops or is broken out of.

While loops have an advantage over for loops in that they’re easier to read in English. For example:

while(ch!=’~’)

This statement says “While the value of variable ch does not equal the tilde character, repeat the following statements.” For this to make sense, you must remember, of course, that ! means not in C. Knowing which sym­

bols to pronounce and which are just decorations is important to understand­ ing C programming.