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

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

The Special Relationship between while and switch-case

Most programs have at their core a while loop. But, within that while loop, they usually have a nice, big switch-case structure. That’s because you can keep choosing options over and over until you choose the option that closes the program. The over-and-over thing is a loop handled by while, and the selection is done by a switch-case structure. To drive this point home, I pre­ sent the final incarnation of the LOBBY.C program:

/* Theater lobby snack bar program */

#include <stdio.h>

int main()

{

char c; int done;

float total=0;

printf(“Please make your treat selections:\n”); printf(“1 - Beverage.\n”);

printf(“2 - Candy.\n”); printf(“3 - Hot dog.\n”); printf(“4 - Popcorn.\n”); printf(“= - Done.\n”); printf(“Your choices:\n”);

/* Figure out what they typed in. */

done=0;

while(!done)

{

c=getchar();

switch(c)

{

case ‘1’: printf(“Beverage\t$8.00\n”); total+=8;

break; case ‘2’:

printf(“Candy\t\t$5.50\n”); total+=5.5;

break; case ‘3’:

printf(“Hot dog\t\t$10.00\n”); total+=10;

break;

Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 249

case ‘4’: printf(“Popcorn\t\t$7.50\n”); total+=7.5;

break; case ‘=’:

printf(“= Total of $%.2f\n”,total); printf(“Please pay the cashier.\n”); done=1;

break;

default:

printf(“Improper selection.\n”);

}/* end switch */

}/* end while */ return(0);

}

Please type the source code for LOBBY3.C into your editor. You can try editing the LOBBY2.C program, if you want, but I have made many subtle changes to the program and wouldn’t want you to miss any. Start from scratch, if you’re willing.

Save the file to disk as LOBBY3.C.

Compile. Fix any errors that may have crept into the code.

Run:

Please make your treat selection: 1 - Beverage.

2 - Candy.

3 - Hot dog.

4 - Popcorn. = - Done. Your choice:

To properly run the program, type your choices all at once and then press the equal-sign (=) key and then Enter. This strategy avoids the buffering problem with the getchar() function, which I could address, but it’s beyond the scope of this chapter.

For example, if you want a beverage and a hot dog, type 13= and then press Enter.

Beverage

$8.00

Hot dog

$10.00

Total of $18.00

 

Please pay the cashier.

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

Run the program again, enter 123412341234xx92431=, and then press Enter:

Beverage

$8.00

Candy

$5.50

Hot dog

$10.00

Popcorn

$7.50

Beverage

$8.00

Candy

$5.50

Hot dog

$10.00

Popcorn

$7.50

Beverage

$8.00

Candy

$5.50

Hot dog

$10.00

Popcorn

$7.50

Improper selection.

Improper selection.

Improper selection.

Candy

$5.50

Popcorn

$7.50

Hot dog

$10.00

Beverage

$8.00

Total of $124.00

 

Please pay the cashier.

This is the last time I’m taking all you guys to the lobby!

Most programs employ this exact type of loop. The while(!done) spins ’round and ’round while a switch-case thing handles all the program’s input.

One of the switch-case items handles the condition when the loop must stop. In LOBBY3.C, the key is the equal sign. It sets the value of the done variable to 1. The while loop then stops repeating.

C views the value 0 as FALSE. So, by setting done equal to 0, by using the ! (not), the while loop is executed. The reason for all this is so that the loop while(!done) reads “while not done” in English.

The various case structures then examine the keys that were pressed. For each match 1 through 4, three things happen: The item that is ordered is displayed on the screen; the total is increased by the cost of that item (total+=3, for example); and a break statement busts out of the switchcase thing. At that point, the while loop continues to repeat as additional selections are made.

You may remember the += thing, from Chapter 16. It’s a contraction of total = total + value.

Part IV

C Level

In this part . . .

Your C language journey has been, I hope, a fun one. Sadly, I have lots more ground to cover, but only a

scant few more pages in which to cover it. Therefore, I collected what I feel are some important concepts that are touched on earlier in this book and present them in this part of the book in a more formal fashion.

This part of the book answers some questions that may have been nagging you from other parts of this book. For example, why is it int main(), and what is the point of the return(0); statement? I discuss what exactly

#include <stdio.h> does as well as provide more infor­ mation on printf() and give you an introduction into arrays, strings, and lots of other fun stuff. So, crack your knuckles and let’s get going!

Chapter 20

Writing That First Function

In This Chapter

Understanding functions

Creating the jerk() function

Prototyping functions

Using the upside-down prototype

Formatting and naming functions

Functions are where you “roll your own” in the C language. They’re nifty little procedures, or series of commands, that tell the computer to do

something. All that’s bundled into one package, which your program can then use repeatedly and conveniently. In a way, writing a function is like adding your own commands to the C language.

If you’re familiar with computer programming languages, you should recognize functions as similar to subroutines or procedures. If you’re not familiar with computer programming (and bless you), think of a function as a shortcut. It’s a black box that does something wonderful or mysterious. After you construct the function, the rest of your program can use it — just like any other C lan­ guage function or keyword. This chapter definitely puts the fun into function.

(This chapter is the first one in this book to lack a clever use of the letter C in the title. Yeah, I was getting sick of it too — C sick, in fact.)

Meet Mr. Function

Are functions necessary? Absolutely! Every program must have at least one function, the main() function. That’s required. Beyond that, you don’t need to create your own functions. But, without them, often your code would con­ tain a great deal of duplicate instructions.

254 Part IV: C Level

A silly example you don’t have to type

Suppose that you write a program that plays “Alexander’s Rag Time Band” every time a user does something pleasing. Because the programming required to play the song is odd and unique, you decide to write a function to conduct the PC’s orchestra. For giggles, suppose that it looks like this:

playAlex()

{

play(466,125);

play(494,375);

play(466,125);

play(494,1000);

/* and there would be more... */

}

Assume that the play() function is used to make the computer’s speaker squawk at a specific pitch for a certain duration. A gaggle of play() functions put together makes the computer whistle a tune.

With all that neatly tucked into a function, your program can then “call” the function every time it wants to play the song. Rather than repeat a vast chorus line of commands, you merely stick the following line into your code:

playAlex();

That’s a C language “command” that says “Go off yonder to said playAlex() function, do what you must while you’re there, and then return to this here very spot to continue a-workin’.” Lo, the function has made writing the pro­ gram easier.

You create a function by writing it in your source code. The function has a name, optional doodads, plus its own C language code that carries out the function’s task. More on this later in this chapter.

To use a function, you call it. Yoo-hoo! You do this by typing the function’s name in your program, followed by the empty parentheses:

playAlex();

This command calls the playAlex() function, and the computer goes off and does whatever it’s instructed to do in that function.

Yes, that’s right. Calling (or using) a function is as easy as sticking its name in your source code, just like any other C language statement.

Some functions require information in their parentheses. For exam­ ple, puts:

puts(“Oh, what a great way to start the day.”);