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

Chapter 17: C You in a While Loop 219

The while true condition that the while loop examines is the same as you find in an if comparison. The same symbols used there are used with while, including ==, <, >, and !=. You can even use the logical dojabbies && (AND) or || (OR), to evaluate multiple comparisons.

When you apply the language of the while loop’s format to HEY.C, you get this:

Starting

Line 7

i=1

While_true

Line 8

i<6

Do_this

Line 11

i++

Notice that, like the for keyword, while lacks a proper semicolon. It’s just followed with a group of statements in curly braces.

If the while loop contains only one statement, you can do without the curly braces:

starting; while(while_true)

do_this;

Some while loops can even be constructed to have no statements. This is rather common:

while((do_this)==TRUE)

;

In this example, the semicolon is the “statement” that belongs to the while loop.

Deciding between a while loop and a for loop

A while loop and a for loop have many similarities — so much so that you would almost seem kooky to use while if you’re fond of for and vice versa. As an example, here’s the basic for loop from the program 100.C, over in Chapter 15:

for(i=1;i<=100;i=i+1)

printf(“%d\t”,i);

This loop counts from 1 to 100 and displays each number.

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

Here’s the same loop à la while:

i=1;

while(i<=100)

{

printf(“%d\t”,i);

i=i+1;

}

See how the for loop was broken up and placed into the while loop? It’s easier to see if I replace the pieces’ parts with big, bold letters. Take a look at this:

for(A;B;C)

printf(“%d\t”,i);

It becomes

A; while(B)

{

printf(“%d\t”,i);

C;

}

Everything is there, but it looks as though the while loop involves even more typing. You could say that if your fingers are tired, you can use a for loop. I like while loops because everything isn’t jammed into one line. It’s easier to see the different parts. Also, you can control the “C” part of the loop in differ­ ent ways, which I get into in later lessons.

Another advantage of the while loop is that it looks more graceful. That’s especially true when you’re replacing what I think are those ugly for(;;) structures. Speaking of which. . . .

Replacing those unsightly for(;;) loops with elegant while loops

Do you remember the following line?

for(;;)

This for loop is repeated forever. Indefinitely. Beyond when the cows come home. Of course, nestled within the loop is a break statement that halts it short, such as when some condition is met. But, meeting a condition to halt a loop — doesn’t that sound like a natural job for a while loop?

Chapter 17: C You in a While Loop 221

Without going through a lot of effort, load the TYPER1.C program into your editor. This program is introduced in Chapter 15 to demonstrate the break key­ word, among other things. The bulk of the program is the following for loop:

for(;;)

{

ch=getchar();

if(ch==’~’)

{

break;

}

}

This example reads “Forever do the following statements.” A character, ch, is read from the keyboard and then checked to see whether a tilde was typed. If so (if TRUE), the loop stops with a break statement.

Go ahead and delete all those lines. Yank! Yank! Yank!

Replace them with these:

while(ch!=’~’)

{

ch=getchar();

}

Oh, this is too easy! The for statement is gone, replaced by a while statement that says to repeat the following statement (or statements) as long as the value of the ch variable doesn’t equal the tilde character. As long as that’s the case, the statement is repeated. And, that sole statement simply reads characters from the keyboard and stores them in the ch variable.

Save the changed source code to disk as TYPER2.C. Compile it and run.

After you see the Press ~ then Enter to stop message, type away. La-la-la. Press the tilde key to stop.

This example shows a while loop elegantly replacing an ugly for loop.

There’s no need for a break statement in this loop because while auto­ matically halts the loop when ch equals a tilde.

The condition checked for by the while loop is negative. It means to keep looping as long as ch does not equal the tilde character. If you had while(ch==’~’), the loop would be repeated only as long as someone kept pressing the tilde key on the keyboard.

The comparison for does not equal is !=, an exclamation point (which means not in C) and an equal sign.

Remember to use single quotes when you’re comparing character constants.

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

Not that it’s worth mentioning, but the endless while loop setup, equiv­ alent to for(;;), is written while(1). In either case, the statements belonging to the loop are repeated indefinitely or until a break statement frees things up.

C from the inside out

Although C can be a strict language, it can also be flexible. For example, just because a function returns a value doesn’t mean that you have to store that value in a variable. You can use the value immediately inside another function.

As an example, consider the getchar() function, which returns a character typed at the keyboard. You can use that character immediately and not store it in a variable. That’s what I call “using C inside out.” It’s one of the more flex­ ible things you can do with C.

The TYPER2.C program is a useful one to illustrate the example of C code being written from the inside out. Here’s what I mean:

while(ch!=’~’)

ch=getchar();

The variable ch is set by the getchar() function. Or, put another way, the getchar() function generates the key press. The ch is just a holding place, and using ch to store that value is merely an intermediate step. To wit:

while(getchar()!=’~’)

;

The drawback is that the character generated by getchar() isn’t saved any­ where. But, it does illustrate a nifty aspect of both the C language and the while loop.

Reedit the TYPER2.C source code so that it looks like this:

#include <stdio.h>

int main()

{

puts(“Start typing.”);

puts(“Press ~ then Enter to stop”);

while(getchar() != ‘~’)

;

printf(“Thanks!\n”);

return(0);

}

Chapter 17: C You in a While Loop 223

There’s no longer a need to declare the variable ch, so that line is gone, as are the curly braces belonging to while.

Save the changes to disk as TYPER3.C. Compile and run.

The output behaves the same — no surprises there. But, the code is much tighter (albeit a little less readable).

Despite this trick, it’s often better to write your code in several steps rather than combine things on one line, “inside out.” By illustrating the several steps, you make your code more readable.

Write things out long-ways first. Then, after you’re certain that the code works, think about recoding from the inside out.

If you do use this trick at any length, be sure to make use of comments to describe what your thinking is. That helps later, in case you ever need to debug your code.

Not to Beat a Dead Horse or Anything. . . .

It has come to this — your first inane programmer joke in C:

while(dead_horse)

beat();

Drawing on your vast knowledge of C, you can now appreciate what humor there is in the “no use beating a dead horse” cliché translated into the C pro­ gramming language. Here are the specifics — if you can hold your sides in long enough:

dead_horse is the name of a variable whose value is either TRUE or FALSE. While dead_horse is TRUE, the loop repeats.

I have also seen the first line written this way:

while(horse==dead) and also while(!alive)

In other words, “While it’s a dead horse. . . .”

The beat() function is repeated over and over as long as the value of dead_horse is TRUE (or as long as horse==dead, in the alternative form).

You don’t have to enclose beat() in curly braces because it’s the only statement belonging to the loop.

Yuck. Yuck. Yuck.

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