
- •Table of Contents
- •Introduction
- •About This Here Dummies Approach
- •How to Work the Examples in This Book
- •Foolish Assumptions
- •Icons Used in This Book
- •Final Thots
- •The C Development Cycle
- •From Text File to Program
- •The source code (text file)
- •The compiler and the linker
- •Running the final result
- •Save It! Compile and Link It! Run It!
- •Reediting your source code file
- •Dealing with the Heartbreak of Errors
- •The autopsy
- •Repairing the malodorous program
- •Now try this error!
- •The Big Picture
- •Other C Language Components
- •Pop Quiz!
- •The Helpful RULES Program
- •The importance of being \n
- •Breaking up lines\ is easy to do
- •The reward
- •More on printf()
- •Printing funky text
- •Escape from printf()!
- •A bit of justification
- •Putting scanf together
- •The miracle of scanf()
- •Experimentation time!
- •Adding Comments
- •A big, hairy program with comments
- •Why are comments necessary?
- •Bizarr-o comments
- •C++ comments
- •Using Comments to Disable
- •The More I Want, the More I gets()
- •Another completely rude program example
- •And now, the bad news about gets()
- •The Virtues of puts()
- •Another silly command-prompt program
- •puts() and gets() in action
- •More insults
- •puts() can print variables
- •The Ever-Changing Variable
- •Strings change
- •Running the KITTY
- •Hello, integer
- •Using an integer variable in the Methuselah program
- •Assigning values to numeric variables
- •Entering numeric values from the keyboard
- •The atoi() function
- •So how old is this Methuselah guy, anyway?
- •Basic mathematical symbols
- •How much longer do you have to live to break the Methuselah record?
- •The direct result
- •Variable names verboten and not
- •Presetting variable values
- •The old random-sampler variable program
- •Maybe you want to chance two pints?
- •Multiple declarations
- •Constants and Variables
- •Dreaming up and defining constants
- •The handy shortcut
- •The #define directive
- •Real, live constant variables
- •Numbers in C
- •Why use integers? Why not just make every number floating-point?
- •Integer types (short, long, wide, fat, and so on)
- •How to Make a Number Float
- •The E notation stuff
- •Single-character variables
- •Char in action
- •Stuffing characters into character variables
- •Reading and Writing Single Characters
- •The getchar() function
- •The putchar() function
- •Character Variables As Values
- •Unhappily incrementing your weight
- •Bonus program! (One that may even have a purpose in life)
- •The Sacred Order of Precedence
- •A problem from the pages of the dentistry final exam
- •The confounding magic-pellets problem
- •Using parentheses to mess up the order of precedence
- •The computer-genie program example
- •The if keyword, up close and impersonal
- •A question of formatting the if statement
- •The final solution to the income-tax problem
- •Covering all the possibilities with else
- •The if format with else
- •The strange case of else-if and even more decisions
- •Bonus program! The really, really smart genie
- •The World of if without Values
- •The problem with getchar()
- •Meanwhile, back to the GREATER problem
- •Another, bolder example
- •Exposing Flaws in logic
- •A solution (but not the best one)
- •A better solution, using logic
- •A logical AND program for you
- •For Going Loopy
- •For doing things over and over, use the for keyword
- •Having fun whilst counting to 100
- •Beware of infinite loops!
- •Breaking out of a loop
- •The break keyword
- •The Art of Incrementation
- •O, to count backward
- •How counting backward fits into the for loop
- •More Incrementation Madness
- •Leaping loops!
- •Counting to 1,000 by fives
- •Cryptic C operator symbols, Volume III: The madness continues
- •The answers
- •The Lowdown on while Loops
- •Whiling away the hours
- •Deciding between a while loop and a for loop
- •Replacing those unsightly for(;;) loops with elegant while loops
- •C from the inside out
- •The Down-Low on Upside-Down do-while Loops
- •The devil made me do-while it!
- •do-while details
- •The always kosher number-checking do-while loop
- •Break the Brave and Continue the Fool
- •The continue keyword
- •The Sneaky switch-case Loops
- •The switch-case Solution to the LOBBY Program
- •The Old switch-case Trick
- •The Special Relationship between while and switch-case
- •A potentially redundant program in need of a function
- •The noble jerk() function
- •Prototyping Your Functions
- •Prototypical prototyping problems
- •A sneaky way to avoid prototyping problems
- •The Tao of Functions
- •The function format
- •How to name your functions
- •Adding some important tension
- •Making a global variable
- •An example of a global variable in a real, live program
- •Marching a Value Off to a Function
- •How to send a value to a function
- •Avoiding variable confusion (must reading)
- •Functions That Return Stuff
- •Something for your troubles
- •Finally, the computer tells you how smart it thinks you are
- •Return to sender with the return keyword
- •Now you can understand the main() function
- •Give that human a bonus!
- •Writing your own dot-H file
- •A final warning about header files
- •What the #defines Are Up To
- •Avoiding the Topic of Macros
- •A Quick Review of printf()
- •The printf() Escape Sequences
- •The printf() escape-sequence testing program deluxe
- •Putting PRINTFUN to the test
- •The Complex printf() Format
- •The printf() Conversion Characters
- •More on Math
- •Taking your math problems to a higher power
- •Putting pow() into use
- •Rooting out the root
- •Strange Math? You Got It!
- •Something Really Odd to End Your Day
- •The perils of using a++
- •Oh, and the same thing applies to a --
- •Reflections on the strange ++a phenomenon
- •On Being Random
- •Using the rand() function
- •Planting a random-number seed
- •Randoming up the RANDOM program
- •Streamlining the randomizer
- •Arrays
- •Strings
- •Structures
- •Pointers
- •Linked Lists
- •Binary Operators
- •Interacting with the Command Line
- •Disk Access
- •Interacting with the Operating System
- •Building Big Programs
- •Use the Command-Line History
- •Use a Context-Colored Text Editor
- •Carefully Name Your Variables
- •Breaking Out of a Loop
- •Work on One Thing at a Time
- •Break Up Your Code
- •Simplify
- •Talk through the Program
- •Set Breakpoints
- •Monitor Your Variables
- •Document Your Work
- •Use Debugging Tools
- •Use a C Optimizer
- •Read More Books!
- •Setting Things Up
- •The C language compiler
- •The place to put your stuff
- •Making Programs
- •Finding your learn directory or folder
- •Running an editor
- •Compiling and linking
- •Index

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

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.”);