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

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

Don’t forget to declare the variable used in for’s parentheses. This common mistake is another one made by just about everyone. Refer to Chapter 8 for more information about declaring variables.

Here’s a handy plug-in you can use for loops. Just substitute the big X in the following line for the number of times you want the loop to work:

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

You must declare i to be an integer variable. It starts out equal to 1 and ends up equal to the value of X. To repeat a loop 100 times, for example, you use this command:

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

Having fun whilst counting to 100

This section has the source code for a program named 100.C. This program uses a for loop to count to 100 and display each number on the screen. Indeed, it’s a major achievement: Early computers could count up to only 50 before they began making wild and often inaccurate guesses about what number came next. (Refer to your phone bill to see what I mean.)

The core of 100.C is similar to OUCH.C. In fact, the only reason I have tossed it in here is that for loops are so odd to some folks that you need two program examples to drive home the point:

#include <stdio.h>

int main()

{

int i;

for(i=1 ; i<=100 ; i=i+1) printf(“%d\t”,i);

return(0);

}

Type this source code into your editor. Watch your indentations; it’s traditional in the C language to indent one statement belonging to another (as shown in the example), even when the curly braces are omitted.

In the for statement, the i variable starts out equal to 1. The while_true condition is i<=100 — which means that the loop works, although the value of variable i is less than or equal to 100. The final part of the statement incre­ ments the value of i by 1 each time the loop works.

Chapter 15: C You Again 193

The printf statement displays the value of the integer variable i by using the %d placeholder. The \t escape sequence inserts a tab into the output, lining up everything by nice, neat columns.

Save the file to disk as 100.C. (It’s a chess-club joke; C in Roman numerals is 100. Hardy-har-har.)

Compile the program and run it. You see 10 rows of 10 columns and numbers 1 through 100 neatly displayed. It’s amazing how fast the computer can do that.

The output shows you the value of the variable i as the for loop works, repeating the printf() statement 100 times and incrementing the value of the i variable 100 times as well.

Change the for statement in Line 5 of your 100.C source code to make the loop go up to 10,000. Use your editor to make it read

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

Just insert 2 extra zeroes after the 100 that are already there. Save the change to disk and recompile. It doesn’t take the computer that much longer to count to 10,000; but it does take longer to display all those numbers.

I’m Bustin’ Outta Here!

Loops are one of the handiest things you can toss into a program — like rich, creamy, high-fat dressing on top of dull (yet cold and crisp) lettuce. It’s only by using loops that programs become useful. Just about anything useful a computer can do for you is accomplished by using a loop: sorting, searching, listing, getting “hung” up. It’s all thanks to loops.

I save the completely loopy lessons for Chapter 17. My task in this section is to round out coverage of the lovely yet foreboding for keyword and show you some interesting anti-loop devices, designed to let you foil the attempts of even the most (over)diligent computer program.

At last — the handy ASCII program

This section has the source code for ASCII.C — which I proudly proclaim as the first useful program in this book. What ASCII.C does is to display the ASCII characters and their corresponding codes, from Code 32 on up to Code 127.

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

This program proves handy because you can more easily type ASCII at the DOS prompt to see the codes than keep looking them up in appendixes. (If you program for any length of time, you look up ASCII codes almost hourly.)

#include <stdio.h>

int main()

{

unsigned char a;

for(a=32;a<128;a=a+1) printf(“%3d = ‘%c’\t”,a,a);

return(0);

}

Enter this source code into your editor. It contains a basic for loop that repeats a printf() statement several dozen times.

After double-checking your work, save the source code to disk as ASCII.C.

Compile the program by using your compiler.

When you run the final result, you see a 5-column display on your screen, illustrating the ASCII characters and their codes, from Code 32 (the “space” character) up to Code 127, which looks like a little house but is really sup­ posed to be the Greek letter Delta (as in ∆ Burke).

I use this program all the time to quickly scope out ASCII code values.

The for loop in the ASCII.C program starts with the value 32. It incre­ ments (by 1) up to the value 127, which is the last stop before a<128. The incrementation is done by the handy a=a+1 equation in the for keyword’s parentheses.

Notice how the printf() function uses the character variable a twice — once as an integer and again as a character. To avoid duplicate output, however, both the %d and %c placeholders are used in printf()’s format string.

The number 3 in printf()’s %3d placeholder directs printf() to always display three characters when it prints the integer value. When you set the display width to three characters, all the code values line up rightjustified (a space is inserted before the 2-digit numbers).

Here’s a secret: The a variable in ASCII.C can be either an integer or a

character variable. Whichever way you declare it, the program works. That’s because in the for loop, a is used as a value, and in the printf() function, it’s used as both a character and a value. This type of duplicity works for both ints and chars, as long as the value never rises higher than 255 (the largest “value” you can store in a char variable).

Chapter 15: C You Again 195

Here’s another secret: The variable a must be declared as an unsigned character. By being unsigned, the possibility of the program dealing with negative numbers is eliminated. If variable a were just a char variable, the loop would repeat endlessly; adding 1 to a when it equals 127 gives a value of –127, and the loop just repeats forever. (To prove it, edit out the word unsigned in the ASCII.C source code and recompile, and then the program runs forever, which probably isn’t what you want.)

Speaking of looping forever. . . .

Beware of infinite loops!

Some things are eternal. Love, they say. Diamonds, of course. Death and taxes, yup. And, some loops can be eternal, though you don’t really want them to be. Eternal is too endearing a term. Moody programmers prefer the term infinite, as in “It goes on forever and never stops.” Yes, it’s kind of like the Energizer bunny.

The infinite loop is a repeating section of your program that is repeated with­ out end. I can think of no practical application for this. In fact, the infinite loop is usually an accident — a bug — that pops up in a well-meaning program. You don’t really know that it’s there until you run the program. Then, when the program just sits there and doesn’t do anything or when something is splashed on the screen again and again, with no hint of stopping, you realize that you have created an infinite loop. Everybody does it.

The following program is FOREVER.C, an on-purpose infinite loop that you can type and try out. Using a misguided for command, the program repeats the printf() statement ad infinitum:

#include <stdio.h>

int main()

{

int i;

for(i=1;i=5;i=i+1)

printf(“The computer has run amok!\n”); return(0);

}

Type this source code into your text editor. It’s similar to the first for-loop pro­ gram in this chapter, OUCH.C. The difference is in the for loop’s “while true” part and the message that is repeated. Save the source code to disk with the name FOREVER.C.

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

Compile the program. Even though the for statement contains a deliberate infinite loop, no error message is displayed (unless you goofed up and typed something else). After all, the compiler may think that you’re attempting to do something forever as part of your master plan. How would it know otherwise?

When you run the program, forever, you see the following messages scrolling madly up your screen:

The computer has run amok!

Indeed, it has! Press Ctrl+C to stop the madness.

Most loops are designed with a condition on which they end. In an end­ less loop, either they don’t have a condition or the condition is set up in some fashion as to be unobtainable. That’s bad.

Infinite loops are insidious! Often, you don’t detect them until the program runs, which is a great argument for testing every program you create.

The Ctrl+C keyboard combination works in both Windows and Unix to cancel a command that is producing standard output, which is what FOREVER.C is doing (over and over). Other types of programs with infi­ nite loops, particularly those that don’t produce standard output, are much harder to stop. If Ctrl+C doesn’t work, often you have to use your operating system’s abilities to kill off the program run amok.

In the olden days, you often had to restart the entire computer to regain control from a run-amok endlessly looping program.

The program loops forever because of a flaw in the for loop’s “while true” part — the second item in the parentheses:

for(i=1;i=5;i=i+1)

The C compiler sees i=5 and figures, “Okay, I’ll put 5 into the i variable.” It isn’t a true-false comparison, like something you find with an if state­ ment, which was expected, so the compiler supposes that it’s true and keeps looping — no matter what. Note that the variable i is always equal to 5 for this reason; even after it’s incremented with i=i+1, the i=5 state­ ment resets it back to 5.

Here’s what the for statement should probably look like:

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

This line repeats the loop five times.

Some compilers may detect the “forever” condition in the for statement and flag it as an infinite loop. If so, you’re lucky. For example, the old Bor­ land C++ compiler flagged FOREVER.C as having a Possibly incorrect assignment error. The compiler still produces the finished (and flawed) program, though.