Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Learn C for Dummies
Description: Notes to Learn C for Dummies - Very Simple and Easy - 411 pages

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


C
FOR

DUMmIES



2ND

EDITION

by Dan Gookin


C
FOR

DUMmIES



2ND

EDITION

C
FOR

DUMmIES



2ND

EDITION

by Dan Gookin


C For Dummies® 2nd Edition
,
Published by
Wiley Publishing, Inc
...
, Indianapolis, Indiana
Published by Wiley Publishing, Inc
...
Requests to the Publisher for permission should be addressed to the Legal Department,
Wiley Publishing, Inc
...
, Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447,
e-mail: permcoordinator@wiley
...

Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies
...
and/or its affiliates in the United
States and other countries, and may not be used without written permission
...
Wiley Publishing, Inc
...

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP­
RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON­
TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE
...
THE ADVICE AND STRATEGIES CONTAINED
HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION
...
IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPE­
TENT PROFESSIONAL PERSON SHOULD BE SOUGHT
...
THE FACT THAT AN ORGANIZATION OR
WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER
INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMA­
TION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE
...

For general information on our other products and services or to obtain technical support, please contact
our Customer Care Department within the U
...
at 800-762-2974, outside the U
...
at 317-572-3993, or fax
317-572-4002
...
Some content that appears in print may
not be available in electronic books
...
He has contributed
articles to numerous high-tech magazines and written more than 90 books
about personal computing technology, many of them accurate
...
Having sold more than
14 million titles translated into more than 30 languages, Dan can attest that
his method of crafting computer tomes does seem to work
...
It became the world’s fastest-selling computer book, at one time
moving more copies per week than the New York Times number-one best
seller (although, because it’s a reference book, it could not be listed on the
NYT best seller list)
...

Dan’s most recent titles include PCs For Dummies, 9th Edition; Buying a Com­
puter For Dummies, 2004 Edition; Troubleshooting Your PC For Dummies; Dan
Gookin’s Naked Windows XP; and Dan Gookin’s Naked Office
...
He also maintains the vast and helpful
Web page www
...
com
...
He lives in the Pacific Northwest, where he enjoys
spending time with his four boys in the gentle woods of Idaho
...
dummies
...

Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media
Development

Production

Project Editor: Rebecca Whitney
Acquisitions Editor: Gregory Croy
Technical Editors: Greg Guntle, Kip Warner
(http://TheVertigo
...
Foxworth
Cartoons: Rich Tennant (www
...
com)

Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary C
...
1
Part I: Introduction to C Programming
...
9
Chapter 2: C of Sorrow, C of Woe
...
29
Chapter 4: C What I/O
...
55
Chapter 6: C More I/O with gets() and puts()
...
73
Chapter 7: A + B = C
...
93
Chapter 9: How to C Numbers
...
121

Part III: Giving Your Programs the Ability

to Run Amok
...
133
Chapter 12: C the Mighty if Command
...
165
Chapter 14: Iffy C Logic
...
185
Chapter 16: C the Loop, C the Loop++
...
215
Chapter 18: Do C While You Sleep
...
239

Part IV: C Level
...
253
Chapter 21: Contending with Variables in Functions
...
275
Chapter 23: The Stuff That Comes First
...
305
Chapter 25: Math Madness!
...
325

Part V: Part of Tens
...
339
Chapter 28: Ten Tips for the Budding Programmer
...
353

Appendix A: The Stuff You Need to Know before You

Read All the Other Stuff in This Book
...
371
Index
...
1
“What Will Understanding C Do for Me?”
...
2
How to Work the Examples in This Book
...
3
Icons Used in This Book
...
4
Final Thots
...
7
Chapter 1: Up from the Primordial C
...
9
The C Development Cycle
...
11
The source code (text file)
...
C source code file
...
14
Compiling GOODBYE
...
15
Running the final result
...
16

Chapter 2: C of Sorrow, C of Woe
...
19
Reediting your source code file
...
21
Dealing with the Heartbreak of Errors
...
22
The autopsy
...
24
Now try this error!
...
29
The Big Picture
...
30
The C Language Itself — the Keywords
...
34
Pop Quiz!
...
36
The importance of being \n
...
37

x

C For Dummies, 2nd Edition
Chapter 4: C What I/O
...
Computer
...
C
...
41
More on printf()
...
42
Escape from printf()!
...
46
A bit of justification
...
49
Putting scanf together
...
51
Experimentation time!
...
55
Adding Comments
...
56
Why are comments necessary?
...
58
Bizarr-o comments
...
60
Using Comments to Disable
...
62

Chapter 6: C More I/O with gets() and puts()
...
65
Another completely rude program example
...
67
The Virtues of puts()
...
68
puts() and gets() in action
...
69
puts() can print variables
...
73
Chapter 7: A + B = C
...
75
Strings change
...
77
Welcome to the Cold World of Numeric Variables
...
78
Using an integer variable in the Methuselah program
...
80
Entering numeric values from the keyboard
...
81
So how old is this Methuselah guy, anyway?
...
Wrinkles
...
86
Basic mathematical symbols
...
88
Bonus modification on the final Methuselah program!
...
91

Chapter 8: Charting Unknown Cs with Variables
...
93
“Why must I declare a variable?”
...
95
Presetting variable values
...
98
Maybe you want to chance two pints?
...
100
Constants and Variables
...
101
The handy shortcut
...
104
Real, live constant variables
...
107
There Are Numbers, and Then There Are Numbers
...
108
Why use integers? Why not just make every number

floating-point?
...
110
Signed or unsigned, or “Would you like a minus sign

with that, Sir?”
...
113
“Hey, Carl, let’s write a floating-point number program!”
...
116
Bigger than the Float, It’s a Double!
...
119

Chapter 10: Cook That C Variable Charred, Please
...
121
Single-character variables
...
123
Stuffing characters into character variables
...
125
The getchar() function
...
127
Character Variables As Values
...
131
Chapter 11: C More Math and the Sacred Order of Precedence
...
133
The old “how tall are you” program
...
136
The Delicate Art of Incrementation (Or, “Just Add One to It”)
...
138
Bonus program! (One that may even have a purpose in life)
...
141
A problem from the pages of the dentistry final exam
...
142
The confounding magic-pellets problem
...
145

Chapter 12: C the Mighty if Command
...
147
The computer-genie program example
...
150
A question of formatting the if statement
...
155
If It Isn’t True, What Else?
...
158
The if format with else
...
160
Bonus program! The really, really smart genie
...
165
The World of if without Values
...
166
The problem with getchar()
...
C to easily read standard input
...
171
Meanwhile, back to the GREATER problem
...
173
Using the if Keyword to Compare Two Strings
...
175
Exposing Flaws in logic
...
177
A solution (but not the best one)
...
178
The if command’s logical friends
...
183

Chapter 15: C You Again
...
185
Repetitive redundancy, I don’t mind
...
188
Tearing through OUCH
...
190
Having fun whilst counting to 100
...
193
At last — the handy ASCII program
...
195
Breaking out of a loop
...
198

Chapter 16: C the Loop, C the Loop++
...
201
Cryptic C operator symbols, Volume I: The inc operator (++)
...
C program
...
204
O, to count backward
...
206
Cryptic C operator symbols, Volume II: The dec operator (--)
...
C
...
209
Leaping loops!
...
211
Cryptic C operator symbols, Volume III:

The madness continues
...
213

Chapter 17: C You in a While Loop
...
215
Whiling away the hours
...
218
Deciding between a while loop and a for loop
...
220
C from the inside out
...
223

xiii


xiv

C For Dummies, 2nd Edition
Chapter 18: Do C While You Sleep
...
225
The devil made me do-while it!
...
227
A flaw in the COUNTDWN
...
228
The always kosher number-checking do-while loop
...
231
Adding a tense, dramatic delay to the COUNTDWN
...
231
The nitty GRID
...
234
Break the Brave and Continue the Fool
...
236
The continue keyword
...
239
The Sneaky switch-case Loops
...
241
The Old switch-case Trick
...
248

Part IV: C Level
...
253
Meet Mr
...
253
A silly example you don’t have to type
...
255
The noble jerk() function
...
C
...
258
Prototypical prototyping problems
...
260
The Tao of Functions
...
262
How to name your functions
...
265
Bombs Away with the BOMBER Program!
...
C program bomb?
...
267
How We Can All Share and Love with Global Variables
...
270
An example of a global variable in a real, live program
...
275
Marching a Value Off to a Function
...
276
An example (and it’s about time!)
...
279
Sending More than One Value to a Function
...
282
Something for your troubles
...
284
Return to sender with the return keyword
...
287
Give that human a bonus!
...
289

Chapter 23: The Stuff That Comes First
...
294
Say! Aren’t you the #include construction?
...
H?
...
298
A final warning about header files
...
302
Avoiding the Topic of Macros
...
305
A Quick Review of printf()
...
306
The printf() Escape Sequences
...
307
Putting PRINTFUN to the test
...
310
The printf() Conversion Characters
...
313
More on Math
...
314
Putting pow() into use
...
317
Strange Math? You Got It!
...
320
The perils of using a++
...
322
Reflections on the strange ++a phenomenon
...
325
On Being Random
...
326
Planting a random-number seed
...
329
Streamlining the randomizer
...
Modulus
...
335

Part V: Part of Tens
...
339
Arrays
...
340
Structures
...
343
Linked Lists
...
344
Interacting with the Command Line
...
345
Interacting with the Operating System
...
346

Chapter 28: Ten Tips for the Budding Programmer
...
347
Keep Your Editor Open in Another Window
...
348
Know the Line-Number Commands in Your Editor
...
350
Know a Few Handy Command-Prompt Commands
...
351
Know Your Post- and Pre-Incrementing and Decrementing Riddles
...
352

Chapter 29: Ten Ways to Solve Your Own Programming

Problems
...
354
Break Up Your Code
...
355
Talk through the Program
...
356

Table of Contents
Monitor Your Variables
...
356
Use Debugging Tools
...
357
Read More Books!
...
359
Setting Things Up
...
360
The place to put your stuff
...
363
Finding your learn directory or folder
...
364
Compiling and linking
...
371
Index
...


Although I can’t promise that you’ll become a C guru after wading through
this text, I can guarantee that you will
ߜ Know how to recognize a C program and, when one is grouped with an IRS
Form 1040, the morning stock report, baseball statistics, and anything
written in Braille, you’ll be able to pick out which one is the C program
...

ߜ Appreciate the following code, but be unable to use it at cocktail parties
to impress your friends:
while(dead_horse)
beat();

ߜ Find out how to speak in C Talk, which is the ability to look at character
groupings, such as printf, putchar, and clock, and pronounce them
as “print-f,” “put-kar,” and “see-lock
...

I can’t really guarantee that last point
...
Let’s leave stern program­
ming up to those who fuss over Avogadro’s number and Fibonacci sequences
and who debate the merits of how to indent their C program source code
...
Fun happens when you read C For Dummies,
2nd Edition
...
Imagine something happening there
...

As long as you know how to program a computer, what you imagine will take
place
...

Programming is the ultimate way to get even with a computer
...

You tell the beast what to do
...
Computers are fast and obedient, not smart
...
The C programming language has been crowned the best and
most common way to program any personal computer
...

It’s tremendously popular and well supported, which makes it a good choice
...

The author may remember that for, oh, maybe two or three chapters
...
So your learning journey ends with a whimper
...

The best way to learn something is one piece at a time
...
That way, you’re not overwhelmed with an initial program
that’s three pages long, and you don’t get lost after a few chapters
...
I insist on it!
This book also gets you started right away
...
That quick!

How to Work the Examples in This Book

Part of the fun of finding out how to program by reading a book is that you
type the programs yourself
...
I sat down with Dr
...
Then I slept
...

Your first task is to read Appendix A
...

Next, you need to know how to type stuff
...
La, la, la
...
Type them all, and press Enter at the end of each line
...
It looks like this:
This is an example of a very long line that was painfully
split in two by this book’s cruel typesetters
...
If you just keep typing, everything fits
on one line on your screen
...


Foolish Assumptions

This book makes the following assumptions about you, your computer, your
compiler, and — most important — your state of mind:
ߜ You have a computer, or at least you have access to one
...

ߜ You’re pretty good with the computer
...
You may
even fix your own problems or help others with their problems
...

ߜ You have a passing familiarity with your operating system’s command
prompt or terminal window
...

ߜ You’re willing to find out how to program — perhaps even desperate to
do so!

Icons Used in This Book
Technical information you can merrily skip over
...


3

4

C For Dummies, 2nd Edition
Something you should remember not to do
...


What’s New with This Edition?

This book isn’t really the second edition of any previous book, but it does
borrow material from the old C For Dummies books, Volumes I and II
...
And, by
reading this book, you’ll have a broad, basic knowledge of the C language
...
Each chapter is self-contained and, where necessary, cross
references to other chapters are included
...
This book has no homework, per se
...
Because of that, those interested in pursuing the C
language further should check out the companion book, C All-in-One Desk
Reference For Dummies (Wiley)
...


Final Thots

Understanding how to use C is an ongoing process
...
” There are new things to be learned
every day and different approaches to the same problems
...

My thoughts on the matter are this: Sure, people who took 20 years of C pro­
gramming and paid too much per semester at A Major University will have
some C snobbishness in them
...
Ask yourself this question: Does my
program run? Okay
...
Does it meet their artifi­
cial standards? Who cares? I’ll be happy if your sloppy C program works
...
You’ll discover new
tricks and adapt your programming style to them
...
c-for-dummies
...
Crack your knuckles,
power up that compiler, and prepare yourself for a few solid hours of eyeball
frazzle
...


ou have never programmed anything in your life
...
You know that you
can punch numbers into your cell phone and hit the Send
button, yet you dare not touch any of the other buttons,
for fear of entering that dark realm, that dank and musty
dungeon of programming
...

Contrary to what you may believe, it’s nothing to program
a computer
...
Programmers may carry
themselves with an air of mysticism and treat their skills
like priests performing sacred religious rites
...

Programming is painless
...
It’s fun
...
In just a few pages, you will be programming
your PC
...


Chapter 1


Up from the Primordial C
In This Chapter
ᮣ Hysterical C history
ᮣ How C programs are created
ᮣ Building the source code
ᮣ Compiling and linking
ᮣ Running the result

A

s the most useful device you have ever used, a computer can become
anything — as long as you have the ability to program it
...
And although
most computer users shy away from programming — confusing it with math­
ematics or electrical engineering — the fact is that programming a computer
is really a rather simple and straightforward thing
...


This chapter introduces you to the basics of programming
...
Feel the power!
Finally, it’s you who can tell the computer what to do with itself!
Because you probably didn’t read this book’s Introduction (for shame), know
that you should preview Appendix A before starting here
...
Then there was the C program­
ming language
...
Programming languages that use
common words and are relatively easy for
most folks to read and study are called highlevel languages
...

High-level languages include the popular BASIC
programming language as well as other lan­
guages that just aren’t that popular any more
...

The lowest of the low-level programming lan­
guages is machine language
...
Machine language con­
sists of numbers and codes that the micro­
processor understands and executes
...

Why would anyone use a low-level language
when high-level languages exist? Speed! Pro­
grams written in low-level languages run as fast
as the computer can run them, often many times
faster than their high-level counterparts
...
A program
written in Visual Basic may be 34K in size, but
the same program written in assembly language
may be 896 bytes long
...
It’s a trade-off
...
It has parts that are lowlevel grunting and squawking, and also many
high-level parts that read like any sentence in a
Michael Crichton novel, but with more charac­
ter development
...
That’s why C is so bitchen
...
C was developed at AT&T Bell Labs in the early 1970s
...
The
next language they created was C — one up on B
...

But you have to admit that the B story is cute enough by itself
...
But, no; it’s named C++, for reasons that become apparent in
Chapter 16
...
See the nearby sidebar, “Stuff you
don’t need to know about language levels,” for the boring details
...
I mention him in case you’re ever walking on the street and you
happen to bump into Mr
...
In that case, you can say “Hey, aren’t
you Dennis Ritchie, the guy who invented C?” And he’ll say “Why — why,
yes I am
...


The C Development Cycle
Here is how you create a C program in seven steps — in what’s known as the
development cycle:
1
...

2
...

3
...

4
...

5
...

6
...

7
...

No need to memorize this list
...
Eventually,
just like shampooing, you start following these steps without thinking about it
...

ߜ The C development cycle is not an exercise device
...

ߜ Step 1 is the hardest
...

ߜ Step 3 consists of two steps: compiling and linking
...
Only later — if you’re still
interested — do I go into the specific differences of a compiler and a
linker
...
Your friends or rela­
tives may refer to you as a “computer wizard” or “guru,” but trust me when I
say that programmer is a far better title
...
” No, the act of writing a pro­
gram is coding
...
Get used to that term! It’s very trendy
...

The object of programming is to “make it happen
...
As the programmer, it’s your job to trans­
late the intentions of the computer user into something the computer under­
stands and then give users what they want
...

The tool you have chosen to make it happen is the C programming language
...
The following sections
describe how the process works
...
Computer programmers
code
...


The source code (text file)

Because the computer can’t understand speech and, well, whacking the
computer — no matter how emotionally validating that is for you — does little
to the PC, your best line of communications is to write the computer a note —
a file on disk
...
This program is a
primitive version of a word processor minus all the fancy formatting and print­
ing controls
...

Using your text editor, you create what’s called a source code file
...
And although it would be nice to write instructions like “Make a
funny noise,” the truth is that you must write instructions in a tongue the com­
puter understands
...


Chapter 1: Up from the Primordial C
ߜ The source code file is a text file on disk
...

ߜ You use a text editor to create the source code file
...


Creating the GOODBYE
...
Carefully type each
line exactly as written; everything you see below is important and necessary
...
h>
int main()
{
printf(“Goodbye, cruel world!\n”);
return(0);
}

As you review what you have typed, note how much of it is familiar to you
...
h, printf, and
that \n thing)
...

Name the file GOODBYE
...
Use the commands in your text editor to save this
file, and then return to the command prompt to compile your instructions
into a program
...

ߜ In Windows Notepad, you must ensure that the file ends in
...
TXT
...
C exten­
sion easier
...
It must be; programming lan­
guages are more than case sensitive — they’re case-fussy
...

ߜ Also note how the program makes use of various parentheses: the angle
brackets, < and >; the curly braces, { and }; and the regular parentheses,
( and )
...
C source code
The first line looks like this:
#include ...
Type a left angle bracket
(it’s above the comma key) and then stdio, a
period, h, and a right angle bracket
...

Press the Enter key alone on the second line to
make it blank
...

And, trust me, anything that makes program­
ming code more readable is okay by me!
Type the word int, a space, main, and then two
parentheses hugging nothing:
int main()

There is no space between main and the
parentheses and no space inside the parenthe­
ses
...

Type a left curly brace:
{

This character is on a line by itself, right at the
start of the line
...


printf(“Goodbye, cruel
world!\n”);

If your editor was smart enough to automati­
cally indent this line, great
...
Then type printf, the word print
with a little f at the end
...
”) Type a left parenthesis
...
Type Goodbye, cruel world, followed by
an exclamation point
...
Press Enter to start the sixth
line
...
Then type return, a paren, 0 (zero), a
paren, and a semicolon
...

On the seventh line, type the right curly brace:
}

Some editors automatically unindent this brace
for you
...
Press the
Enter key to end this line
...


The compiler and the linker

After the source code is created and saved to disk, it must be translated into
a language the computer can understand
...

The compiler is a special program that reads the instructions stored in the
source code file, examines each instruction, and then translates the information
into the machine code understood only by the computer’s microprocessor
...
It’s a middle step, one that isn’t necessary
for smaller programs but that becomes vital for larger programs
...

If either the compiler or the linker doesn’t understand something, an error
message is displayed
...

Then go back and edit the source code file again, fixing whatever error the
compiler found
...
) Then you attempt to compile
the program again — you recompile and relink
...
The linker then converts that infor­
mation into a runnable program
...
An object file is created by GCC, but it is
automatically deleted when the final program file is created
...
The first part of the
object file name is the same as the source code filename
...

ߜ Text editor➪Compiler
...


Compiling GOODBYE
...
Assuming that
you have thumbed through it already, use your powerful human memory to
recall the proper command to compile and link the GOODBYE
...

Here’s a hint:
gcc goodbye
...

Well?
Nothing happens! If you have done everything properly, the GCC compiler
merely creates the final program file for you
...


15

16

Part I: Introduction to C Programming
If you do get an error, you most likely either made a typo or forgot some tiny
tidbit of a character: a missing “ or ; or \ or ) or ( or — you get the idea
...
Use the editor to fix your mistake, save the code to
disk, and then try again
...
In any event, note that Chapter 2 covers error-hunting
in your C programs
...
So why not run that program!
In Windows, the command to type is
goodbye

In the Unix-like operating systems, you must specify the program’s path or
location before the program name
...
/goodbye

Press the Enter key and the program runs, displaying this marvelous text on
your screen:
Goodbye, cruel world!

Welcome to C language programming!
(See Appendix A for more information on running programs
...
They are save, com­
pile, link, and run
...

Save! Saving means to save your source code
...


Chapter 1: Up from the Primordial C
Compile and link! Compiling is the process of transforming the instructions
in the text file into instructions the computer’s microprocessor can under­
stand
...
(Again, your compiler may do this step automatically
...
Yes, it’s a legitimate pro­
gram, like any other on your hard drive
...
That’s how C programs are built
...
(But by then, getting your program
to run correctly and without errors is the hardest part!)
You find the instructions to save, compile, and run often in this book
...
What’s more important is
understanding how the language works
...


17

18

Part I: Introduction to C Programming

Chapter 2


C of Sorrow, C of Woe
In This Chapter
ᮣ Reediting and recompiling
ᮣ Fixing an error
ᮣ Understanding the error message
ᮣ Dealing with heinous linker errors

D

on’t let the success of a first-time compile spoil an otherwise normal
day of programming
...
Those errors have
to be fixed
...


This chapter gets you used to the idea of errors and how to deal with them
...
That must mean that
dealing with errors is a larger part of the programming picture than you may
have otherwise imagined
...
Big deal! But just once, type pirntf
rather than printf and your entire programming world becomes unglued
...
One missing curly brace can lead to a screen
full of embarrassing error messages
...
Errors
happen
...
Like this:
1
...

2
...

3
...

Errors can still happen
...

ߜ It happens
...
Note Steps 4 and 6
...


Reediting your source code file

Source code is not carved in stone — or silicon, for that matter
...
Sometimes, the changes are necessary, in the case of errors and
boo-boos
...
To do that, you have to reedit your source code file
...
To do so,
use your editor and change the source code file, replacing the original mes­
sage with your newer, pithier message
...
Use your text editor to reedit the GOODBYE
...

2
...
Replace the text Goodbye, cruel world! with Farewell, you ugly
toad!
printf(“Farewell, you ugly toad!\n”);

Change only the text between the double quotes
...
Everything else — don’t touch!

Chapter 2: C of Sorrow, C of Woe
4
...

5
...

It’s okay to overwrite the original; your modified file becomes the new
GOODBYE
...

Now you’re ready to recompile your source code, as covered in the next
section
...

ߜ You reedit the source code file to repair an error caught by the compiler
or linker or to modify the program
...

ߜ If you’re using the command prompt to run your editor, don’t forget that
you can use the up-arrow key to recall previous commands (in certain
command-prompt environments)
...
C source
code file reappears at the prompt
...
This process usually hap­
pens after you modify or change the source code, such as you do in the pre­
ceding section
...

To recompile the new GOODBYE
...
For most everyone, that’s
gcc goodbye
...
The new program has been created
...
/goodbye —
at the prompt to see the new, stunning output
...
That is how you fix an error or modify the program
...

ߜ If you see any errors after recompiling, you must re-reedit your source
code and then re-recompile again
...
)

Dealing with the Heartbreak of Errors

Errors happen
...
Every day
...
Consider them learning tools or
gentle reminders
...
Contrast this with your most night­
marish math class: The wicked pedant would write only “WRONG!” next to your
calculations, no matter how innocent a mistake you made
...


Yikes! An error! But, before

you shoot yourself
...
C
...
It’s a flawed
C program, one that contains an error (albeit an on-purpose error):
#include ...
\n”)
return(0);
}

Type the source code exactly as it appears here
...
C
source code as a base; start over here with a clean editor window
...
C
...


Chapter 2: C of Sorrow, C of Woe
Unfortunately, when you compile this program, it produces an error
...

ߜ Pay careful attention as you type! Each little oddball character and nutty
parenthesis is important to the C language!
ߜ Here’s a hint on the common GCC command to compile this source code:
gcc error
...
C program erred! What a shock
...
(In fact, you may have seen this type of
error before
...
c: In function `main’:
error
...
Still, what the error message lacks
in personality, it makes up for in information
...
What­
ever your compiler, you should be able to single out the following bits of
information:
ߜ The source code file that contained the error, error
...

Most important, you’re given a line number: The error is in Line 6
...
(You can
cut the compiler some slack here
...
A parse, or syntax, error means that an item
of C language punctuation is missing, and, therefore, two things that aren’t
supposed to run together have run together
...


23

24

Part I: Introduction to C Programming
The solution? You have to reedit the source code file and fix what’s wrong
...
C and add the semicolon to the end of
Line 5
...
If so, your eyes would wander back and — because
you’re aware of the Missing Semicolon Syndrome — you would see the prob­
lem and mend it
...

ߜ Syntax refers to the way a language is put together
...
” Eh
...
Beyond that, GCC is
remarkably consistent with its error messages
...
You find out in the next chapter more about semicolons and the
role they play
...
That’s why nearly all text editors use line numbers, which you can
see at the top or bottom of the screen or editing window
...
In the case of a missing
semicolon, the next line may be the “error line
...
Oh, well — at least it’s close and not
a generic honk of the speaker and “ERRORS GALORE, YOU FOOL” plas­
tered onscreen
...
Often, the
first error is the only real one, but the compiler lists others that follow
because it becomes confused
...
That is the evil of the statement “Do what I mean”: Computers can’t
read minds, so you must be precise
...


Repairing the malodorous program

To make the world right again, you have to fix the program
...


Chapter 2: C of Sorrow, C of Woe

No need to fill your head with this
C programming has two degrees of errors:
warnings and errors
...
(Sounds like a mistake
Roger Ebert would make
...

The warning error means “Ooo, this doesn’t
look tasty, but I’ll serve it to you anyway
...
Or, it may just be that the

compiler is being touchy
...

The critical error means “Dear Lordy, you tried
to do something so criminal that I cannot
morally complete this program
...
But the compiler cannot
complete its task because it just doesn’t under­
stand your instructions
...
C program by adding a semicolon
...
Also correct the sentence displayed on the
screen so that it reads as follows:
printf(“This program will no longer err
...

Save ERROR
...
Recompile the program and then run it:
This program will no longer err
...
ERROR
...
When you
get an error message, you should check it to see where the error is in your
source code
...
That way, you find what’s wrong
...

ߜ Pull two Rs out of ERRORS and you have Eros, the Greek god of love
...
Replace the C in Cupid with St and you have
Stupid
...
C file just yet
...
(If you did, use your editor to load the ERROR
...
)
Change Line 6 in the ERROR
...
Otherwise, the zero in the parentheses
and the semicolon are unchanged
...
The compiler couldn’t care less
...
That’s because it’s the linker that glues program files together
...

And, like any frazzled librarian, the linker spews forth an error message
...
C file to disk
...
Brace yourself for an
error message along the lines of
temporary_filename
...
o: undefined reference to ‘retrun’

Or, the message may look like this:
temporary_filename
...
c: undefined reference
to ‘retrun’

It’s harder to tell where the error took place here; unlike compiler errors,
linker errors tend to be vague
...
So, rather than use a line-number
reference, you can always just search for the bogus text
...

Save
...
The linker should be pleased
...

ߜ If the linker is run as a separate program, it obviously produces its own
error messages
...
O — which you can see in the error message output
...


Chapter 2: C of Sorrow, C of Woe
ߜ The linker’s job is to pull together different pieces of a program
...
” So the error
slides by
...


All about errors!
A common programming axiom is that you don’t
write computer programs as much as you
remove errors from them
...

Compiler errors: The most common error, ini­
tially discovered by the compiler as it tries to
churn the text you write into instructions the
computer can understand
...
The errors
are caught before the program is built
...
In advanced C programming, when
you’re working with several source files, or mod­
ules, to create a larger program, linker errors
may involve missing modules
...

Pieces of the program are built, but errors pre­
vent it from them being glued together
...
They aren’t bugs; instead, they’re
things that look totally acceptable to the com­
piler and linker but just don’t do quite what you
intended
...
) The most
common run-time error is a null pointer assign­
ment
...
The
program is built, but usually gets shut down by
the operating system when it’s run
...
The
compiler diligently creates the program you
wrote, but whether that program does what you
intended is up to the test
...
Bugs
include everything from things that work slowly
to ones that work unintentionally or not at all
...

The program is built and runs, but it doesn’t
behave the way you think it would
...
Your native tongue has a certain
cadence or word pattern
...

Foreign languages, they have weird characters: ç, ü, and ø and letter combi­
nations that look strange in English — Gwynedd, Zgierz, Qom, and Idaho
...
You need a road map to know
what’s what
...
That’s what this chapter shows
...


The Big Picture

Figure 3-1 outlines the GOODBYE
...

Each program must have a starting point
...
As its last dockmaster duty, the OS hurls the microprocessor headlong into the program
...


30

Part I: Introduction to C Programming

1
3

Figure 3-1:
GOODBYE
...


Main

function


2

4

6

8

#include ...
Every C program
has one; GOODBYE
...
C, and all the other C programs you ever create
...
The main()
function is also the skeleton upon which the rest of the program is built
...
C programs can have other functions, but main() is the first one
...
The parentheses can be
empty, or they can contain information — it all depends on the individ­
ual function
...

ߜ A function is a machine — it’s a set of instructions that does something
...
It’s required
...
Get used to that word
...
#include is known as a preprocessor directive, which sounds impressive,
and it may not be the correct term, but you’re not required to memorize it
anyhow
...
Doing this avoids lots of little,
annoying errors that would otherwise occur
...
...
The
whole statement #include ...
H and stick it into your source code before the source
code is compiled
...
H file itself contains information about the
STanDard Input/Output functions required by most C programs
...
” You read more about header files in Chapter 23
...
int main does two things
...
Second, that line names the function main, which also
identifies the first and primary function inside the program
...

4
...
Sometimes, items may
be in these parentheses, which I cover in Chapter 22
...
All functions in C have their contents encased by curly braces
...


6
...
It’s job is to display information on the screen
...
The added f means
“formatted,” which you find out more about in the next few chapters
...
Like all C language functions, printf() has a set of parentheses
...
Everything between
the double quote characters (“) is part of printf’s text string
...
An interesting part of the text string is \n
...
What it represents is the character produced by pressing
the Enter key, called a newline in C
...

9
...
The semicolon is
C language punctuation — like a period in English
...
Note that
all statements require semicolons in C, even if only one statement is in a
program or function
...
The second statement in GOODBYE
...
This
command sends the value 0 (zero) back to the operating system when
the main() function is done
...
You read why in Chapter 22
...


31

32

Part I: Introduction to C Programming
ߜ Text in a program is referred to as a string
...
The string is enclosed by double quotes
...
Then come a set
of curly braces, { and }
...

ߜ The C language is composed of keywords that appear in statements
...

(Don’t frazzle your wires over memorizing this right yet
...
C has only 32 keywords
...


Table 3-1

C Language Keywords

auto

double

int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed

void

default

goto

sizeof

volatile

do

if

static

while

Not bad, eh? But these aren’t all the words you use when writing programs in
C
...
These include jewels like
printf() and several dozen other common functions that assist the basic C
language keywords in creating programs
...
This concept is completely beyond the grasp of the modern
legal community
...
For example, you cannot
think up your own function and name it short
...
That’s one way the keywords are special
...
Still,
I would avoid using them in your programs
...
)
Also, the C++ language has a hoard of reserved
words
...


In addition to grammar, languages require rules, exceptions, jots and tittles,
and all sorts of fun and havoc
...

ߜ The keywords can also be referred to as reserved words
...
This sentence is always true for C:
Keywords, as well as the names of functions, are lowercase
...

ߜ You are never required to memorize the 32 keywords
...

ߜ Some keywords are real words! Others are abbreviations or combinations
of two or more words
...

ߜ Each of the keywords has its own set of problems
...


33

34

Part I: Introduction to C Programming
ߜ Functions such as printf() require a set of parentheses and lots of stuff
inside the parentheses
...
”)
ߜ By the way, the fact that printf() is a C function and not a keyword is
why the #include ...
The STDIO
...
If you edit out the #include ...


Other C Language Components

The C language has many other parts, making it look rather bizarre to the new
programmer
...
Instead, keep these few points
rolling around in your mind, like so many knowledge nuggets:
ߜ The C language uses words — keywords, functions, and so forth — as its
most basic elements
...
Sometimes these symbols are called
operators, and at other times they’re called something else
...

ߜ The words have options and rules about how they’re used
...

You don’t have to memorize all of them, though a few of them become
second nature to you as you study and use C
...

The words are put together to create statements, which are similar to
sentences in English
...

ߜ Braces are used to group parts of a program
...
In Figure 3-1 and in all your C programs
in the first two chapters, for example, the braces have been used to con­
tain the belongings of the main() function
...
Syntax is how languages are put
together
...
The core function in every C language program is called
A
...

B
...

C
...

D
...

2
...
The “words” of the C language
...
Held together with string and earwax
...
Uttered only in candlelit reverence by the C Language Gurus
...
As numerous as the stars and nearly as distant
...
In addition to keywords are
A
...

B
...

C
...

Man, do we have a bracket problem!
D
...

4
...
They talk in whispers
...
The parentheses keep the function warm
...
The parentheses hold various things required by or belonging to
the function
...
What’s a function?
5
...
Using what you know of
C, draw in the braces where they should appear in the following program:
int main()
___
printf(“Goodbye, cruel world!\n”);
return(0);
___

Answers on page 516
...
To help you under­
stand the most easily offended C rules, I have summarized them in the follow­
ing program
...
h>
int main()
{
printf(“Braces come in pairs!”);
printf(“Comments come in pairs!”);
printf(“All statements end with a semicolon!”);
printf(“Spaces are optional!”);
printf(“Must have a main function!”);
printf(“C is done mostly in lowercase
...
”);
return(0);
}

Type the preceding source code into your editor
...
C
...

The resulting program is named RULES, and you can run it whenever you
need a reminder about some basic C do’s and don’ts
...
It merely has more printf() functions
...
That’s
because it’s split between two lines
...


The importance of being \n

Did you notice something odd about the output of the RULES program? Yes, it
resembles an ugly clot of text:
Braces come in pairs!Comments come in pairs!All statements
end with a semicolon!Spaces are optional!Must have
a main function!C is done mostly in lowercase
...


The source code looks okay, but what’s missing from the output is the char­
acter you get when you press the Enter key, or what’s called the newline char­
acter
...
It’s that weird \n thing:

Chapter 3: C Straight
\n

This line is C-speak for “Gimme a new line of text
...

The program you just created, RULES
...

This addition makes the output of the RULES program easy to read
...
C source code file again
...


If you’re good with search and replace, search for the “) (quote-paren) and
replace it with \n”)
...
The output should now be more pleasing:
Braces come in pairs!
Comments come in pairs!
All statements end with a semicolon!
Spaces are optional!
Must have a main function!
C is done mostly in lowercase
...


ߜ In C, the \n character is used in a text string as though the Enter key were
pressed
...
C is mostly lowercase
...

ߜ Table 24-1, in Chapter 24, lists other characters of a similar nature to \n
...
When used to end a line, the sole \ tells the compiler
that the rest of the line is merely continued on the line that follows
...
\n”);

are both seen as one single line when it comes time to compile; all the compiler
sees is this:
printf(“C is done mostly in lowercase It’s a case-sensitive
language
...
The \ simply lets you split up a long line between several lines
in your source code
...

Depending on how your editor and compiler behave, the result of splitting a
line with a string of text in it may not be what you want
...

sensitive language
...
The solution is merely to edit the source code so that the extra
tabs are removed from the string of text
...
\
It’s a case-sensitive language
...
\
It’s a case-sensitive language
...
Save that
mess
...
The output shall be most pleasing to the eye
...

ߜ Don’t worry about using the \ to split any lines
...

ߜ Although split lines are treated as a single line, any errors that happen on
either line are given their proper line number in the source code file
...
C example,
the compiler would flag it on that line, not on the line before it
...
The wimminfolk would want to dance
real slow
...
It was a sentimental thing, y’all — something that fancy,
dooded-up city slickers read about in dime magazines
...
This goes along with what I present in Chapter 3: It is your
job as a programmer to write a program that does something
...
Soon, however, you begin to write pro­
grams that really do something
...
Computer

To meet the needs of input and output — the old I/O — you can try the follow­
ing program, WHORU
...
Please
don’t go calling this program “horror-you” (which could be spelled another
way, but this is a family book)
...
h>
int main()
{
char me[20];
printf(“What is your name?”);
scanf(“%s”,&me);
printf(“Darn glad to meet you, %s!\n”,me);
return(0);
}

Type the preceding source code into your editor
...


Don’t bother with any details just yet
...


Save the file to disk
...
C
...
That happens in the next section
...
It provides storage for
the information you enter (the I in I/O)
...

ߜ The new function here is scanf(), which is used to read input from the
keyboard and store it in the computer’s memory
...
Right paren is the ) character
...
(It’s also not a “real” word and
is frowned on by English teachers of the high-and-tight bun
...
C

Compile the WHORU
...
If you see syntax or other errors, doublecheck your source code with what is listed in this book
...
Be on the lookout for jots and tittles — parentheses,
double quotes, backslashes, percent signs, sneeze splotches, or other unusual
things on your monitor’s screen
...
Otherwise, keep reading in the next
section
...

ߜ A common beginner error: Unmatched double quotes! Make sure that you
always use a set of “s (double quotes)
...

Also make sure that the parentheses and curly braces are included in
pairs; left one first, right one second
...
Type whoru or
...
The output looks like this:
What is your name?

The program is now waiting for you to type your name
...

If you typed Buster, the next line is displayed:
Darn glad to meet you, Buster!

ߜ If the output looks different or the program doesn’t work right or gener­
ates an error, review your source code again
...

ߜ I/O is input/output, what computers do best
...

ߜ This program is an example that takes input and generates output
...

The WHORU
...
The rest of this chapter
tells more about these common and useful functions in detail
...
It’s the all-purpose “Hey, I want to tell the user
something” display-text command
...


41

42

Part I: Introduction to C Programming
The format for using the basic printf function is
printf(“text”);
printf is always written in lowercase
...
It’s followed by parentheses,
which contain a quoted string of text, text (see the example)
...

In the C language, printf()is a complete statement
...
(Okay, you may see an exception, but it’s not worth
fussing over at this point in the game
...

ߜ You have to follow special rules about the text you can display, all of which
are covered in Chapter 24
...
A more advanced
format for printf() appears later in this chapter
...


It’s a simple collection of text, numbers, letters, and other characters — but
it’s not a string of text
...
For those characters to be considered as a unit,
they must be neatly enclosed in double quotes:
“Ta da!

I am a text string
...
For manipulation, you need to wrap up the string in the bunlike parentheses:
(“Ta da!

I am a text string
...

Put printf on one side and a semicolon on the other:
printf(“Ta da!

I am a text string
...
Neat and tidy
...


Is this criminal or what? It’s still a text string, but it contains the double-quote
characters
...
””

Now there are four double quotes in all
...
How can it morally cope with that?
“”Damocles” if I know
...
There is no large
room in a hollowed-out mountain in the Rockies where a little man sits in a
chair looking at millions of video screens, one of which contains your PC’s
output, and, no, the little man doesn’t snicker evilly whenever you get an
error
...
C
...
But this time, what’s dis­
played contains a double quote
...
h>
int main()
{
printf(“He said, “Ta da! I am a text string
...
(You notice right away that something is wrong if your editor color-codes
quoted text
...
)
Save the source code file to disk as DBLQUOTE
...

Compile and run the preceding program — if you can
...
c: In function ‘main’:
dblequote
...
c: In function ‘main’:
dblequote
...
Your
compiler knows that
...
” Therefore, an error was generated
...


The error happened
right here, Officer
...
"");

printf()

statement
...

The question is how to pass that character along to printf() without it ruin­
ing the rest of your day
...

In the olden days, programmers would have simply gone without certain char­
acters
...
Some ancient programmers who don’t know about escape
sequences still use these tricks
...
In a programming
language, escape sequences are used to sneak otherwise forbidden characters,
or characters you cannot directly type at the keyboard, into text strings
...
Locate this character on your keyboard now
...

The backslash character signals the printf() function that an escape
sequence is looming
...


Chapter 4: C What I/O
To sneak in the double-quote character without getting printf() in a tizzy,
you use the escape sequence \” (backslash, double quote)
...
\””);

Notice the \” escape sequences in the text string
...
The two
outside double quotes, the ones that really are bookmarks to the entire string,
remain intact
...

(If your text editor color-codes strings, you see how the escaped double quotes
appear as special characters in the string, not as boundary markers, like the
other double quotes
...
C source code file
...
All you have to do is insert two backslash char­
acters before the rogue double quotes: \”
...
C
file with the newer version
...
This time, it works and displays the following output:
He said, “Ta da! I am a text string
...

ߜ Another handy escape sequence you may have used in Chapter 1 is \n
...

You cannot “type” the Enter key in a text string, so you must use the \n
escape sequence
...

ߜ How do you stick a backslash character into a string? Use two of them:
\\ is the escape sequence that sticks a backslash character into a string
...
Essentially,
the \ thing is a shorthand notation for sticking forbidden characters into
any string
...


45

46

Part I: Introduction to C Programming

The f means “formatted”

The function is called printf() for a reason
...
The
advantage of the printf function over other, similar display-this-or-that func­
tions in C is that the output can be formatted
...
]]);

What appears in the double quotes is really a formatting string
...

After the format string comes a comma (still inside the parentheses) and then
one or more items called arguments
...
You can use printf() to display
the content or value of one or more variables
...
Figure 4-2 illustrates this concept
rather beautifully
...
\n", str, num);
Figure 4-2:
How
printf()

solves
arguments
...
] doohickey means that you can have any number of var items
specified in a single printf function (before the final paren)
...
They must match up, or else you get an error when the
program is compiled
...
C
...
h>
int main()
{
printf(“%15s”,”right\n”);
printf(“%-15s”,”left\n”);
return(0);
}

What JUSTIFY
...
This makes more sense when you see the program’s output
rather than just look at the source code
...

In the first printf statement, the first string is %15s (percent sign, 15, little s)
...

The second printf statement is nearly the same thing, though with a minus
sign before the 15 and the string left rather than right
...
Be careful with what you type! When
you’re certain that you have it right, save the file to disk as JUSTIFY
...

Compile JUSTIFY
...
Fix any errors if you need to
...
Your
output should look something like this:
right
left

The word right is right-justified 15 spaces over; left is left-justified
...

The %15s part of the formatting string didn’t print at all
...
That’s the formatting
power of printf() at work
...
C program into your text
editor
...

The formatting string is %s, which is the string
(for s) placeholder
...

Save the source code under a new filename,
BYE
...
Compile and run
...

Try this modification of Line 5:
printf(“%s, %s
%s\n”,”Goodbye”,”cruel”,
”world!”);

Carefully edit Line 5 to look like what’s shown in
the preceding line
...
Save
...

Run
...

(If you get a compiling error, you probably have
put a comma inside the double quotes, rather
than between them
...
C program shows you only a hint of what the printf() function
can do
...

ߜ In the printf() function, the first item in quotes is a formatting string,
though it can also contain text to be displayed right on the screen
...
It identifies a
conversion character — what I call a “placeholder” — that tells printf
how to format its output
...

ߜ Any numbers between the % and the s are used to set the width of the text
string displayed
...
A minus sign before the 15 means to left-justify the string’s output
...


Chapter 4: C What I/O
ߜ All this conversion-character stuff can get complex
...
Often, advanced programmers have to
consult their C language references and run some tests to see which for­
matting command does what
...


scanf Is Pronounced “Scan-Eff”

Output without input is like Desi without Lucy, yang without yin, Caesar salad
without the garlic
...
” Besides — and this may be the most horrid aspect
of all — without input, the computer just sits there and talks at you
...

C has numerous tools for making the computer listen to you
...

ߜ scanf() is a function like printf()
...

ߜ Like the f in printf(), the f in scanf() means formatted
...
In
this chapter, however, you just use scanf() to read a line of text, noth­
ing fancy
...
First, you need a storage place
to hold the text you enter
...

The storage place is called a string variable
...
Variable means that the string isn’t set — it can be what­
ever the user types
...
(Variables are discussed at length in Chapter 8
...
Its format is somewhat similar
to the advanced, cryptic format for printf(), so there’s no point in wasting
any of your brain cells covering that here
...
First, you create
a storage place for the first name:
char firstname[20];

This C language statement sets aside storage for a string of text — like creating
a safe for a huge sum of money that you wish to have some day
...

Here’s how the preceding statement breaks down:
char is a C language keyword that tells the compiler to create a character

variable, something that holds text (as opposed to numbers)
...
When the source code
refers to the variable, it uses this name, firstname
...
All told, you have set aside space to hold 20 characters and
named that space — that variable — firstname
...

The next step is to use the scanf() function to read in text from the keyboard
and store it in the variable that is created
...

%s is the string placeholder; scanf() is looking for plain old text input

from the keyboard
...

The text input is stored in the string variable named firstname
...

The semicolon ends the C language statement
...
The next section coughs up
an example
...
For text input, that place is a string variable, which you create
by using the char keyword
...
For now, con­
sider the string variable that scanf() uses as merely a storage chamber
for text you type
...
In real life, you use them mostly with printf() because
there are better ways to read the keyboard than to use scanf()
...

ߜ Forgetting to stick the & in front of scanf()’s variable is a common mis­
take
...
As a weird quirk, however, the
ampersand is optional when you’re dealing with string variables
...


The miracle of scanf()

Consider the following pointless program, COLOR
...
It asks for your name and then your favorite color
...

#include ...
Save this file to disk as COLOR
...

Compile
...
A
common mistake: forgetting that there are two commas in the final printf()
statement
...
\color

The reason is that COLOR is a valid console command in Windows XP, used
to change the foreground and background color of the console window
...
You have to figure it out for yourself
...
C program:
printf(“%s’s favorite color is %s\n”,color,name);

The order of the variables here is reversed: color comes first and then name
...
The program still runs, but the output
is different because you changed the variable order
...


See? Computers are stupid! The point here is that you must remember the
order of the variables when you have more than one listed in a printf()
function
...

How about making this change:
printf(“%s’s favorite color is %s\n”,name,name);

This modification uses the name variable twice — perfectly allowable
...
Save this change and recompile
...
(Better learn to order your variables now
...
A string constant is
simply a string enclosed in quotes
...
(It isn’t variable!)
Save the change to disk and recompile your efforts
...

ߜ The string constant “blue” works because printf()’s %s placeholder
looks for a string of text
...
(Of course, the advan­
tage to writing a program is that you can use variables to store input;
using the constant is a little silly because the computer already knows
what it’s going to print
...

ߜ You need one string variable in the printf() function for each %s that
appears in printf()’s formatting string
...

ߜ In addition to string variables, you can use string constants, often called
literal strings
...

(I have to demonstrate it here, however, or else I have to go to C Teacher’s
Prison in Connecticut
...
This advice
is especially important when you use both numeric and string variables
in printf
...
Om! If you want a percent sign
(%) to appear in printf’s output, use two of them: %%
...
I’m not talking about the programming itself — that’s easy
to remember, and you can buy books and references galore in case you don’t
...
You do that by inserting a comment in your
source code
...
Comments don’t begin to become necessary until you write larger
programs — on the scope of Excel or Photoshop — where you can easily lose
your train of thought
...
That way, when
you look at the source code again, your eyes don’t glaze over and the drool
doesn’t pour, because the comments remind you of what’s going on
...
Every­
thing between those two points is ignored by the compiler, meaning that you
can stick any text in there — anything — and it doesn’t affect how the pro­
gram runs
...
What follows is another example of
a comment, but the type that gives this book its reputation:
/*
Hello compiler! Hey, error on this: pirntf!
Ha! Ha! You can’t see me! Pbbtbtbt!
Nya! Nya! Nya!
*/

ߜ The beginning of the comment is marked by the slash and the asterisk: /*
...

ߜ Yup, they’re different
...
You do not need a semi­

colon after the */
...
C
...
C Source Code

Written by (your name here)

*/

#include ...
The only thing new should be the
comments
...
Make sure that you get
those right: A slash-asterisk begins the comment, and an asterisk-slash ends
it
...
)
Save the file to disk and name it MADLIB1
...

Compile
...

Here is a sample of the program’s output:
Enter
Enter
Enter
Enter

an adjective:hairy
a food:waffle
a household chore (past tense):vacuumed
an item of furniture:couch

Don’t touch that hairy waffle!
I just vacuumed the couch!

Oh, ha-ha! Ouch! My sides!
ߜ This program is long and looks complex, but it doesn’t use any new tricks
...
Yawn
...
C uses these four string variables: adjective, food, chore, and
furniture
...
Each of the string variables is filled
by scanf() with your keyboard input
...
Two
string variables in each function supply the text for the %s placeholders
...
These characters separate the input section, where you enter the
bits of text, from the program’s output
...

ߜ MADLIB1
...
Make sure that you can find each one
...


57

58

Part I: Introduction to C Programming

Why are comments necessary?

Comments aren’t necessary for the C compiler
...
Instead, com­
ments are for you, the programmer
...
You can put any­
thing in the comments, though the more useful the information, the better it
helps you later on
...
All my C programs start
with information such as the following:
/* COOKIES
...
m
...

*/

These lines tell me what the program is about and when I started working on it
...

*/

The point is that comments are notes for yourself
...
If you work on a large programming project, the comments
placate your team leader
...


Comment Styles of the Nerdy
and Not-Quite-Yet-Nerdy
The MADLIB1
...
Though you can comment your programs in many more ways,
these are the most common:

Chapter 5: To C or Not to C
/*
MADLIB1
...
The first line starts
the comment with the /* all by itself
...
The final line ends the
comment with */ all by itself
...

/* Get the words to use in the madlib */

This line is a single-line comment, not to be confused with a C language state­
ment
...
It’s
100 percent okey-dokey, and, because it’s not a statement, you don’t need a
semicolon
...


Bizarr-o comments

During my travels, I have seen many attempts to make comments in C programs
look interesting
...
It contains lots of asterisks, but they’re all still stuck
between /* and */, making it a viable comment
...

*/

59

60

Part I: Introduction to C Programming
The idea in this example is to create a “wall of asterisks” between the /* and
*/, making the comment stick out on the page
...
For example, I may put a line of asterisks between dif­
ferent functions so that I can easily find them
...


C++ comments

Because today’s C compilers also create C++ code, you can take advantage
of the comment style used by C++ in your plain old C programs
...

In C++, comments can start with a double slash, //
...
The end of the line marks the end of the
comment:
//This is another style of comment,
//one used in C++

This commenting style has the advantage that you don’t have to both begin
and end a comment, making it ideal for placing comments at the end of a C
language statement, as shown in this example:
printf(“Enter an adjective:”);
scanf(“%s”,&adjective);

// prompt
// input

These modifications to the MADLIB1
...
This method is preferred because it’s quick; however, /* and */ have
the advantage of being able to rope in a larger portion of text without typing
// all over the place
...
No matter what lies between the /*
and the */, it’s skipped over
...

Modify the MADLIB1
...
Insert a line with /* on it before the first printf() function in this
example
...
Insert a line with */ on it after the second printf() function
...
It runs as before, but the resulting “mad lib” isn’t displayed
...

ߜ You can use comments to disable certain parts of your program
...
” You
may also want to include a note to yourself, explaining why that section
is commented out
...
The reason is that you may have accidentally commented
it out
...

ߜ By using an editor with color-coded text, you can easily spot missing */
characters to end a comment
...


61

62

Part I: Introduction to C Programming

The Perils of “Nested” Comments

The most major of the faux pas you can commit with comments is to “nest”
them, or to include one set of comments inside another
...
However, notice that the display_error function has a comment
after it: erno is already set
...
You comment out
everything except that line to get it to work:
/*
if(all_else_fails)
{
display_error(erno);
walk_away();
}
else
*/
get_mad();

/* erno is already set */

Here, the C compiler sees only the get_mad function, right?
Wrong! The comment begins on the first line with the /*
...
Because that line ends with */ — the
comment bookend — that’s the end of the “comment
...
The second comment bookend (just above
the get_mad() function) also produces an error
...

This example shows a nested comment, or a comment within a comment
...
Figure 5-1 illustrates how the C compiler interprets the nested
comment
...
The solution in this case is to uncomment
the erno is already set comment
...
The extra /*
inside the comment is safely ignored
...

ߜ Note that the C++ style of comments, //, doesn’t have a nesting problem
...


More errors!
AC
K!

63

64

Part I: Introduction to C Programming

Chapter 6


C More I/O with gets()

and puts ()

In This Chapter
ᮣ Reading strings of text with gets()

ᮣ Avoiding some gets() problems

ᮣ Using puts() to display text

ᮣ Displaying variables with puts()

ᮣ Knowing whether to use puts() or printf()


T

he printf() and scanf() functions aren’t the only way you can display
information or read text from the keyboard — that old I/O
...
Until then, you’re
stuck with what C offers
...
gets()
reads a string of text from the keyboard, and puts() displays a string of text
on the screen
...
Both do the
same thing: They read characters from the keyboard and save them in a vari­
able
...
scanf() can read in numeric values
and strings and in a number of combinations
...


66

Part I: Introduction to C Programming
Like scanf() reading in text, gets() requires a char variable to store
what’s entered
...
Here’s the format:
gets(var);
gets(), like all functions, is followed by a set of parentheses
...
Inside the parentheses
is var, the name of the string variable text in which it is stored
...
C program
...
C program, introduced in Chapter 4, except that gets() is used
rather than scanf()
...
h>
int main()
{
char jerk[20];
printf(“Name some jerk you know:”);
gets(jerk);
printf(“Yeah, I think %s is a jerk, too
...
Save the file to disk and name it
INSULT1
...

Compile the program
...
Remember your
semicolons and watch how the double quotes are used in the printf()
functions
...
The output looks something like this:
Name some jerk you know:Bill
Yeah, I think Bill is a jerk, too
...
Yet no matter what
reads it, the printf() statement can display it
...

ߜ If you get a warning error when compiling, see the next section
...
“Get a string of
text from the keyboard
...
” “Get string” works for me, though
...
That’s
because gets() is not considered a safe, secure function to use
...
This
flaw, known as a keyboard overflow, is used by many of the bad guys out there
to write worms and viruses and otherwise exploit well-meaning programs
...
It’s okay here
as a quick way to get input while finding out how to use C
...


The Virtues of puts()

In a way, the puts() function is a simplified version of the printf() function
...

puts() is just a boneheaded “Yup, I display this on the screen” command
...
That can either be a string variable name or a string of text in double
quotes
...
The puts() function is a complete
C language statement, so it always ends with a semicolon
...
It’s
like puts() “presses Enter” after displaying the text
...


67

68

Part I: Introduction to C Programming

Another silly command-prompt program

To see how puts() works, create the following program, STOP
...
Yeah, this
program is really silly, but you’re just starting out, so bear with me:
#include ...
”);
return(0);
}

Save this source code to disk as STOP
...
Compile it, link it, run it
...
/stop at
the command prompt:
Unable to stop: Bad mood error
...

ߜ puts() is not pronounced “putz
...
The text
is hugged by double quotes and is nestled between two parentheses
...
For example,
you can use \” if you want to display a string with a double quote in it
...
puts()
always displays the newline character at the end of its output
...


puts() and gets() in action

The following program is a subtle modification to INSULT1
...
This time, the
first printf() is replaced with a puts() statement:
#include ...
”,jerk);
return(0);
}

Load the source code for INSULT1
...
Change Line 7 so that it
reads as just shown; the printf is changed to puts
...
C
...
Compile
...

Name some jerk you know:
Rebecca
Yeah, I think Rebecca is a jerk, too
...
That’s why input takes place on the next line
...
Other­
wise, the program runs the same as INSULT1
...


More insults

The following source code is another modification to the INSULT series of pro­
grams
...

Here’s how it looks:
#include ...
”,jerk);
return(0);
}

Load the source code for INSULT2
...
Make the changes just
noted, basically replacing the printf in Line 9 with puts
...

Save the new source code to disk as INSULT3
...
Compile and run
...
c:9: too many arguments to function ‘puts’

The compiler is smart enough to notice that more than one item appears to
be specified for the puts() function; it sees a string, and then a variable is
specified
...
Oops
...

ߜ If you got the program to run — and some compilers may — the output
looks like this:
Name some jerk you know:
Bruce
Yeah, I think that %s is a jerk, too
...
To puts(), the %s in a string is just %s — characters — nothing
special
...
Why a line by
itself? Because no matter what, puts() always tacks on that pesky newline
character
...


Consider the following source code, the last in the INSULT line of programs:
#include ...
”);
return(0);
}

Chapter 6: C More I/O with gets() and puts()
Feel free to make the preceding modifications to your INSULT3
...
Save the changes to disk as INSULT4
...
Compile
...

Name some jerk you know:
David
Yeah, I think
David
is a jerk, too
...
But the program works the way it was
intended
...
For one, puts() automatically sticks a newline on
the end of a string it displays
...
And, last, the next bit of code shows the program the way it
should be written by using only puts() and gets()
...
Then you must stick something in the variable, which
you can do by using the scanf() or gets function
...

ߜ Do not use puts() with a nonstring variable
...
(See
Chapter 8 for the lowdown on variables
...


ߜ Use printf() to display the contents of
more than one variable at a time
...


ߜ Use printf() when you don’t want the
newline (Enter) character to be displayed
after every line, such as when you’re
prompting for input
...


ߜ Use printf() when fancy formatted
output is required
...


rogramming a computer involves more than just
splattering text on a screen
...
After all, computers have
their roots in the calculators and adding machines of years
gone by
...

I have to admit: Programming a computer does involve
math
...
Before you go running and screaming
from the room, however, consider that it’s the computer
that does the math
...
Perdomo
glowering at you like a fat hawk eyeing a mouse, you merely
have to jot down the problem
...

Relax! Sit back and enjoy reading about how you can slav­
ishly make the computer do your math puzzles
...


Chapter 7


A+B=C
In This Chapter
ᮣ Changing a variable’s value
ᮣ Introducing the int
ᮣ Converting text with the atoi() function
ᮣ Using +, -, *, and /
ᮣ Struggling with basic math

I

t’s time to confirm your worst fears
...
But it’s more of a passing fancy than the infatuation you’re now
dreading
...
You add, subtract, divide,
multiply, and maybe do a few other things
...
It’s really fourth-grade stuff, but because
we work with variables— which is more like eighth-grade algebra stuff — this
material may require a little squeezing of the brain juices
...


The Ever-Changing Variable

A variable is a storage place
...
You do this by using a smattering of C lan­
guage keywords that you soon become intimate with
...
That’s why it’s called a vari­
able
...

The contents can change too — just like the psychic prediction or campaign
promise
...
When
you play PacMan, for example, his position on the screen is kept in a vari­
able because, after all, he moves (his position changes)
...
And, when you win the
game, you enter your name, and that too is stored in a variable
...

ߜ Variables are information-storage places in a program
...

ߜ The contents of a variable? It depends
...
Their contents depend on what
happens when the program runs, what the user types, or the computer’s
mood, for example
...

ߜ Where are variables stored? In your computer’s memory
...


Strings change

The following program is brought to you by the keyword char and by the
printf() and gets() functions
...
The
changing contents of kitty show you the gist of what a variable is:
#include ...
What else do you have in
mind?”,kitty);
gets(kitty);
printf(“%s is nice, too
...
C into your text editor
...
C
...
C
...
Check for
missing semicolons, misplaced commas, and so on
...

Running the program is covered in the next section
...

ߜ Only by assigning text to the variable can its contents be read
...


Running the KITTY

After compiling the source code for KITTY
...
The output looks something like this:
What would you like to name your cat?Rufus
Rufus is a nice name
...


The kitty variable is assigned one value by using the first gets() function
...
Though the
same variable is used, its value changes
...

ߜ A single variable can be used many times in a program
...

ߜ It’s the contents of the string variable that are displayed — not the vari­
able name
...
C program, the variable is named kitty
...
What’s stored in the variable is
what’s important
...
This allows you to work with values in your program and
to do the ever-dreaded math
...
Unlike char, which creates all types of strings,
different keywords are used to create variables for storing different types of
numbers
...


Hello, integer

To keep things sane for now, I show you only one of the numeric variable
types
...
Just say “IN-tuh-jur
...

Here’s how the typical C compiler defines an integer type of number:
ߜ An integer is a whole number — no fractions, decimal parts, or funny
stuff
...

ߜ Negative numbers, from –32,768 up to 0 are also allowed
...
5 — are not integers
...
)
To use an integer variable in a program, you have to set aside space for it
...
Here’s
the format:
int var;

The keyword int is followed by a space (or a press of the Tab key) and then
the name of the variable, var
...

ߜ Some compilers may define the range for an int to be much larger than
–32,768 through 32,767
...

ߜ On older, 16-bit computers, an integer ranges in value from –32,768
through 32,767
...

ߜ More information about naming a variable — and other C language trivia
about variables — is offered in Chapter 8
...


Chapter 7: A + B = C
ߜ Yes! You’re very observant
...
Without getting
too far ahead, you should now recognize that main() is known as an
“integer function
...

ߜ Computer geeks worldwide want you to know that an integer ranges from
–32,768 up to 0 and then up to 32,767 only on personal computers
...
Yeah, this information is completely
optional; no need cluttering your head with it
...


Using an integer variable in
the Methuselah program
If you need only small, whole-number values in a C program, you should use
integer variables
...
Other examples of using integer variables are
to store the number of times something happens (as long as it doesn’t happen
more than 32,000-odd times), planets in the solar system (still 9), corrupt
congressmen (always less than 524), and number of people who have seen
Lenin in person (getting smaller every day)
...

The following program displays the age of the Biblical patriarch Methuselah,
an ancestor of Noah, who supposedly lived to be 969 years old — well
beyond geezerhood
...
C, from Methus, which was
his nickname:
#include ...
\n”,age);
return(0);
}

Enter the text from METHUS1
...
Save the file to disk as
METHUS1
...


79

80

Part II: Run and Scream from Variables and Math
Compile the program
...
Recompile
...


The variable age was assigned the value 969
...

ߜ The fifth line creates the age variable, used to store an integer value
...
The variable age comes first, and then the equal sign, and
then the value (969) to be placed in the age variable
...
In printf()’s formatting string, the %d conversion charac­
ter is used as a placeholder for an integer value
...


Assigning values to numeric variables

One thing worth noting in the METHUS1 program is that numeric variables
are assigned values by using the equal sign (=)
...
That’s the way it is, was, and shall be in the C language:
var=value;

var is the name of the numeric variable
...
Read it as “The value of the variable var is equal to the value value
...
So shoot me
...
Anything that pops out a value — an integer
value, in this case — is acceptable
...
C, the value for the variable age is assigned directly:
age=969;

Lo, the value 969 is safely stuffed into the age variable
...
The
variable goes on the left side of the equal sign and gets its value from
whatever’s on the right side
...

You cannot say
kitty=”Koshka”;

It just doesn’t work! Strings can be read into variables from the keyboard
by using the scanf(), gets(), or other C language keyboard-reading
functions
...
C program warm in your editor’s oven for a few seconds
...
Because the value 969 is already in the pro­
gram, there’s no surprise
...
Who knows what wacky value the user may enter?
(That’s another reason for a variable
...
And, there’s most definitely a dif­
ference between the characters “969” and the number 969
...
(I leave it up to you to figure out which is which
...
The secret command to do it is atoi, the A-to-I function
...
The A comes from the acronym ASCII,
which is a coding scheme that assigns secret code numbers to characters
...
” That’s
how you can read integers from the keyboard
...
That’s followed by an equal sign, which is how you assign a value to
a variable
...
A numeric value is what
you find lurking in a numeric variable
...

A value is 5 apples, 3
...
Those are values
...

When you type 255, for example, you’re enter­
ing a string
...
The string “255”
is not a value
...
By using the

atoi() function in the C language, you can

translate it into a value, suitable for storage in a
numeric variable
...
Which
is which? It depends on how you’re going to use
it
...
(My zip code is 94402, but that doesn’t
mean that it’s the 94-thousandth-something
post office in the United States
...


The atoi() function follows the equal sign
...
The string can be a string variable or
a string “constant” enclosed in double quotes
...

The line ends in a semicolon because it’s a complete C language statement
...
h>

This line is usually placed below the traditional #include ...
h in the angle pinchers
that’s required here
...

ߜ atoi is not pronounced “a toy
...

ߜ Numbers are values; strings are composed of characters
...


Chapter 7: A + B = C
ߜ The purpose of #include ...
Without that line, you may see some warning or “no
prototype” errors, which typically ruin your programming day
...
H is the standard library header file, don’t you know
...
That’s how you translate input from the keyboard into
a numeric value: You must squeeze a string by using a special function
(atoi) and extract a number
...
C, a gradual, creeping improvement over
METHUS1
...
In this version of the program, you read a string that the user
types at the keyboard
...
Then, that
value is displayed by using the printf() function
...

#include ...
h>
int main()
{
int age;
char years[8];
printf(“How old was Methuselah?”);
gets(years);
age=atoi(years);
printf(“Methuselah was %d years old
...
C source code into your editor
...
C source code, but be careful to save it to disk under the
new name, METHUS2
...

Compile the program
...

Run the program
...


83

84

Part II: Run and Scream from Variables and Math

No, you don’t have to experiment with METHUS2
...
Unlike that sober tome, this book
allows you to freely fiddle, poke, pull, experi­
ment, and have fun
...

Run the METHUS2
...
Press Enter and the output tells you
that the old guy was 1,410,065,408 years old —
or some other value, not what you typed
...
The value returned is the
remainder of what you entered divided by the
maximum size of an integer in your compiler
...
M
...
The reason is
that integer values include negative numbers
...
5

Is the oldest human really four-and-a-half?
Probably at one time
...
That’s because the point­
5 part is a fraction
...

Finally, the big experiment
...
But when you enter old into the
program, it claims that he was only zero
...
Therefore, it gener­
ates a value of zero
...
That was entered as a string,
transformed by atoi() into an integer value and, finally, displayed by
printf()
...
Other sections
in this chapter, as well as in the rest of this book, continue to drive home
this message
...
But by using this program, you
can really twist history (though Methuselah probably had lots of con­
temporaries who lived as long as you and I do)
...
h> thing or you misspell it, a few
errors may spew forth from your compiler
...
Regardless, get

Chapter 7: A + B = C
in the habit of including the stdlib thing when you use the atoi()
function
...
The atoi() function examines the string and spits
up a number
...

ߜ Why not just print the string years? Well, you can
...
To wit:
printf(“Methuselah was %s years old
...
However, only with a numeric variable can you
perform mathematical operations
...
Wrinkles

Time to modify the old Methuselah program again
...
C source code, as shown next
...
C, only subtle
modifications are made to the original program
...

#include ...
h>
int main()
{
int methus;
int you;
char years[8];
printf(“How old are you?”);
gets(years);
you=atoi(years);
printf(“How old was Methuselah?”);
gets(years);
methus=atoi(years);
printf(“You are %d years old
...
\n”,methus);
return(0);
}

Double-check your source code carefully and save the file to disk as
METHUS3
...


85

86

Part II: Run and Scream from Variables and Math
Compile METHUS3
...
Fix any errors that sneak into the picture
...
You’re asked two questions, and then two strings of text
are displayed — something like the following:
How old are you?29
How old was Methuselah?969
You are 29 years old
...


Of course, this data is merely regurgitated
...
Don’t sweat it!
ߜ You’re not really 29
...
First, it reads in your age,
and then the atoi() function converts it and saves the value in the you
variable
...
This strategy works because
the original value was saved in another variable — a cool trick
...
C program has been divided into four sections
...
The idea is to write the program in paragraphs — or
thoughts — similar to the way most people try to write English
...
No, wait! Please
don’t leave
...
The first real math explanation is several pages
away
...
Second, you have
to know what to do with the results
...
That’s what the computer is for
...
Here they are:

Chapter 7: A + B = C
ߜ Addition symbol: +
ߜ Subtraction symbol: –
ߜ Multiplication symbol: *
ߜ Division symbol: /
Incidentally, the official C language term for these dingbats is operators
...

+ Addition: The addition operator is the plus sign, +
...

– Subtraction: The subtraction operator is the minus sign, –:
var=value1-value2;

Here, the result of subtracting value2 from value1 is calculated and gently
stuffed into the numeric variable var
...
The multiplication operator is
the asterisk — not the × character:
var=value1*value2;

In this line, the result of multiplying value1 by value2 is figured out by the
computer, and the result is stored in the variable var
...

Note that in all cases, the mathematical operation is on the right side of the
equal sign — something like this:
value1+value2=var;

87

88

Part II: Run and Scream from Variables and Math

Why the multiplication symbol is an asterisk
(if you care to know)
In school, you probably learned that the X symbol
means multiply
...
It’s pro­
nounced “times,” as in “four times nine” for 4×9
...
” I have even
seen that expressed as 4(9) or (4)(9), though I fell
right back asleep
...
” So, the asterisk (*) was accepted as a
substitute
...
)
Using the * for multiplication takes some getting
used to
...
But the * takes some chanting
and bead counting
...
The computer doesn’t

It just doesn’t work in the C language
...
Huh? And
that’s the kind of error you see when you try it: Huh? (It’s called an Lvalue
error, and it’s shamefully popular
...

This chapter introduces only the four most common symbols
...

ߜ Unlike in the real world, you have to keep in mind that the calculation is
always done on the right, with the answer squirted out the equal sign to
the left
...
You can work with a variable and a value, two variables,
functions — lots of things
...


How much longer do you have to live
to break the Methuselah record?
The following METHUS4
...


Chapter 7: A + B = C
Before you do this, I want you to think about it
...
He was a good man, well received
by The Man Upstairs
...

#include ...
h>
int main()
{
int diff;
int methus;
int you;
char years[8];
printf(“How old are you?”);
gets(years);
you=atoi(years);
methus=969;

/* Methuselah was 969 years old */

diff=methus-you;
printf(“You are %d years younger than
Methuselah
...
C program is eerily similar to METHUS3
...
It has only a few
deviations, so you can edit the METHUS3
...
C
...

Compile the program
...
Then run the final
product
...


Try entering a different age to see how it compares with Methuselah’s
...
years is a string variable
...
Pay special attention to the order
of events in the following statement:
diff=methus-you;

The math part always goes on the right side of the equal sign
...
The result then slides through the
equal sign and into the diff numeric variable
...
Because he got his
first job at 19, he has been contributing to Social Security
...
And out
...
And out some more
...
)
#include ...
h>
int main()
{
int contributed;
int received;
contributed=65-19;
received=969-65;
printf(“Methuselah contributed to Social Security for
%i years
...
\n”,received);
return(0);
}

Type into your editor the source code for METHUS5
...
Double-check your typing and
all that stuff
...

Save the file as METHUS5
...


Chapter 7: A + B = C
Compile it! Check for any errors or small pieces of meat the compiler may
choke on
...

Run the program! Here’s a sample of the output:
Methuselah contributed to Social Security for 46 years
...


ߜ It seems fair to him
...
If he died at 969 and began receiving checks at 65, the differ­
ence is the value you want
...

ߜ Notice how the smaller value is subtracted from the larger? C works
from left to right with math: 65 minus 19; 969 minus 65
...
The variable that holds the
result is on the left
...

ߜ You can find more information on the subject of constants in Chapter 8
...
In the last few
Methuselah programs, the values were known, for the most part
...
Otherwise, con­
stant values can be used
...
You
don’t have to type this program, but look at the only two statements in the
program
...
h> because atoi() isn’t being
used:
#include ...
\n”,65-19);
printf(“Methuselah collected from Social Security for
%d years
...
” The printf() function expects to find that value after the comma —
and it does! The value is calculated by the C compiler as 65–19, which is 46
...
The
same holds true for the second printf() function
...
You can figure out 65–19 and
969–65 in your head and then plug in the values directly:
printf(“Methuselah contributed to Social Security for
%d years
...
\n”,904);

Again, the result is the same
...
It doesn’t matter to printf() whether the
value is a constant, a mathematical equation, or a variable
...


Chapter 8


Charting Unknown Cs

with Variables

In This Chapter
ᮣ Declaring variables
ᮣ Naming variables
ᮣ Using float variables
ᮣ Declaring several variables at once
ᮣ Understanding constants
ᮣ Creating constants with #define
ᮣ Using the const keyword

V

ariables are what make your programs zoom
...
You may have just dabbled with variables, but not
been formally introduced
...

Valerie is a numeric variable
...
Whenever she sees an equal sign, she takes to a value and
holds it tight
...
In
that way, Valerie is a little flaky
...


94

Part II: Run and Scream from Variables and Math
Victor is a string variable
...
As long as it’s a character, Victor doesn’t
mind
...

ߜ Yes, I have a point here
...

ߜ The C language has several different types of numeric variables, depend­
ing on the size and precision of the number
...

ߜ Before you use a variable, it must be declared
...


“Why must I declare a variable?”

You’re required to announce your variables to the C compiler before you use
them
...
That way, the compiler knows what the variables are called and
what flavor of variables they are (what values they can contain)
...

For example:
int count;
char key;
char lastname[30];

Three variables are declared in this example: an integer variable, count; a
character variable, key; and a character variable, lastname, which is a string
that can be as many as 30 characters long
...
First, it says “These things are variables!” That way, when the compiler
sees lastname in a program, it knows that it’s a string variable
...
The compiler knows that integer values fit into the count variable,
for example
...
This can’t be done “on the fly,” as the program runs
...


Chapter 8: Charting Unknown Cs with Variables
ߜ Declare your variables near the beginning of your program, just after the
line with the initial curly brace
...

ߜ Obviously, you don’t know all the variables a program requires before
you write it
...
) If you need a new vari­
able, use your editor to declare it in the program
...

ߜ If you don’t declare a variable, your program doesn’t compile
...

ߜ Most C programmers put a blank line between the variable declarations
and the rest of the program
...
For example:
int count; /* busy signals from tech support
...
You have to
follow a few rules, and you cannot use certain names for variables
...
To avoid that, try to keep the following guidelines in the back of your
head when you create new variables:
ߜ The shortest variable name is a letter of the alphabet
...
Single-letter variables are just
hunky-dory
...
Short, descriptive variable names are best
...
(All of C is lowercase, for the most
part
...

ߜ Uppercase letters can be used in your variables, but most compilers
tend to ignore the differences between upper- and lowercase letters
...
)

95

96

Part II: Run and Scream from Variables and Math
ߜ You shouldn’t begin a variable name with a number
...
Even if your compiler says that it’s
okay, other C compilers don’t, so you should not begin a variable name
with a letter
...
This technique is fine,
though it’s not recommended to begin a variable name with an under­
line
...
Don’t name your integer variable int, for example, or your string
variable char
...
(Refer to Table 3-1, in Chapter 3, for
a list of the C language keywords
...
Little L looks too much like a 1 (one), and O looks too
much like a 0 (zero)
...
For example, the compiler
may assume that forgiveme and forgivemenot are the same variable
...

ߜ Buried somewhere in the cryptic help files that came with your compiler
are the official rules for naming variables
...
After all, I’m not
paid by the hour
...


Presetting variable values

Suppose that this guy named Methuselah is 969 years old
...

If you were going to use Methuselah’s age as a value in a program, you could
create the variable methus and then shove the value 969 into it
...
First comes the declaration:
int methus;

This line tells the compiler that methus is capable of holding an integer-size
value in its mouth and all that
...
For example:
int methus=969;

This statement creates the integer variable methus and assigns it the value
969 — all at once
...
(C is full of short­
cuts and alternatives — enough to make you kooky
...

Normally, string variables are created and given a size
...
Then you use gets() or scanf() to stick text into that variable
...
That string variable already
contains the text “So how fat are you, anyway?” Notice that you see no number
in the brackets
...
No guesswork —
what joy!
ߜ Numeric variables can be assigned a value when they’re declared
...
Remember to
end the line with a semicolon
...
For
example:
int video=800*600;

This statement creates the integer variable video and sets its value
equal to 800 times 600, or 480,000
...
)
ߜ Even though a variable may be assigned a value, that value can still
change
...

After all, a variable is still a variable
...
Each of them is set equal to 0
...
You probably see this
type of declaration used more often than you end up using it yourself
...
C program was concocted
...
Ah
...
Here’s the source code:
#include ...
45;
printf(“Today special - %s\n”,menuitem);
printf(“You want %d pint
...
\n”,price);
return(0);
}

Type this source code into your editor
...
Save the
program as ICKYGU
...

Compile the program
...

Run the final program
...

That be $1
...


Whoa! Is that lira or dollars? Of course, it’s dollars — the dollar sign in
printf()’s formatting string is a normal character, not anything special
...
45 value was printed with four extra zeroes
...
That’s just the way the %f, or floating-point conver­
sion character, displays numbers
...
2f:
printf(“That be $%
...
\n”,price);

Squeezing extra characters between the % and the f should be familiar to
you; I show you how to it a few chapters back, to limit the formatting for the
%s placeholder
...

Save the change to disk
...
The output is more appealing:
Today special - Slimy Orange Stuff “Icky Woka Gu”
You want 1 pint
...
45, please
...

ߜ The price is a floating-point value because it contains a decimal part
...
Unlike an integer, floating-point values
can contain a decimal part
...
45 —
which is technically incorrect, but it’s the way I remember it
...
There, you find that %f is used to display a floating-point number,
such as the one that appears in ICKYGU
...

ߜ The final printf() statement is used to display the value of the floatingpoint price variable:
printf(“That be $%
...
\n”,price);

To do that, you use the %f (f for float) placeholder
...

To meet this end, you insert a “dot-2” between the % and the little f
...
Rather than use %f, the
formatting string uses %
...


Maybe you want to chance two pints?

You can easily twist ICKYGU
...
Suppose that
you want to figure out how much two pints of the orange stuff is
...
Then you have to stick some math into
the final printf() function, which calculates how much two pints of the sticky
stuff would be
...
2f, please
...
Before, you had only the
price variable
...
Because price is a floating-point, or decimal,
value, the result still is floating-point
...

Save these changes and recompile the program
...


Multiple declarations

C is full of abbreviations and shortcuts
...
One such trick is to declare several variables in one statement
...

The following three int statements create three integer variables: methus,
you, and diff:
int methus;
int you;
int diff;

The following single-line statement does the same thing:
int methus,you,diff;

Each of the variables is specified after the int keyword and a space
...

This shortcut is primarily a space-saving technique
...

You can declare variables of only the same type in a multiple declaration
...

Keep variables that are defined with a value on a line by themselves
...

It’s used like a variable, though its value never changes
...
In this type of program, you have to use the dreaded value π (pi)
...
1415926 (and on and on)
...

Another example of a constant is a quoted string of text:
printf(“%s”,”This is a string of text”);

The text “This is a string of text” is a constant used with this
printf() function
...

ߜ A constant is used just like a variable, though its value never changes
...

ߜ π is pronounced “pie
...
We pronounce the English
letter p as “pee
...
This chapter, therefore, con­
centrates primarily on numeric constants
...
Then one day, you’re faced with a
program like SPEED
...
h>
int main()
{
printf(“Now, the speed limit here is %i
...
\n”,55+15);
printf(“Didn’t you see that %i MPH sign?\n”,55);
return(0);
}

Start over with a new slate in your editor
...
There’s nothing new or repulsive in it
...
C
...

But I clocked you doin’ 70
...

But what if the speed limit were really 45? That would mean that you would
have to edit the program and replace 55 with 45 all over
...

ߜ You can easily argue that this isn’t a problem
...
Unfortunately, searching and replacing
numbers in a computer program is a dangerous thing to do! Suppose that
the number is 1
...
141 — all those would be goofed up by a search-andreplace
...
After all, was the scofflaw
doing 70 or 60? To me, it doesn’t matter
...


The handy shortcut

The idea in this section is to come up with a handy shortcut for using
number constants in C
...


Chapter 8: Charting Unknown Cs with Variables
The first solution is to use a variable to hold the constant value:
int speed=55;

This line works because the compiler sticks the value 55 into the speed inte­
ger variable, and you can then use speed rather than 55 all over your program
...
The compiler goes to all that work, fluffing up the pillows
and making things comfy for the variable, and then you misuse it as a con­
stant
...
It’s really cinchy, as the updated SPEED
...
h>
#define SPEED 55
int main()
{
printf(“Now, the speed limit here is %i
...
\n”,SPEED+15);
printf(“Didn’t you see that %i MPH sign?\n”,SPEED);
return(0);
}

Several changes are made here:
ߜ The program’s new, third line is another one of those doohickeys that
begins with a pound sign (#)
...
In fact,
two big boo-boos with #define are using an equal sign and ending the
line with a semicolon
...

ߜ The shortcut word SPEED is then used in the program’s three printf()
statements to represent the value 55
...

Secretly, what happens is that the compiler sees the #define thing and all by
itself does a search-and-replace
...
The advantage is that you can easily
update the constant values by simply editing the #define directive
...
C source code so that it matches what you see
listed here
...
It has the same
output because your only change was to make the value 55 a real, live con­
stant rather than a value inside the program
...
If you edit Line 3 to read
#define SPEED 45

you have effectively changed the constant value 45 in three other places
in the program
...
C program —
but it saves you even more time for longer, more complex programs that
also use constant values
...


The #define directive

The #define construction (which is its official name, though I prefer to call
it a directive) is used to set up what the C lords call a symbolic constant — a
shortcut name for a value that appears over and over in your source code
...
It’s traditional to name
it like a variable and use ALL CAPS (no spaces)
...
It’s replaced by that value globally
throughout the rest of your source code file
...


No semicolon is at the end of the line, but notice that the line absolutely must
begin with a pound sign
...

You should also tack a comment to the end of the #define line to remind you
of what the value represents, as in this example:
#define SPEED 55

/* the speed limit */

Here, SPEED is defined to be the value 55
...


Chapter 8: Charting Unknown Cs with Variables
A string constant can be created in the same way, though it’s not as popular:
#define GIRLFRIEND “Brenda”

/* This week’s babe */

The only difference is that the string is enclosed in double quotes, which is a
traditional C-string thing
...
Other than that, the rules that apply to variable
names typically apply to the shortcut words
...

ߜ You have to keep track of which types of constants you have defined and
then use them accordingly, as shown in this example:
printf(“The speed limit is %i
...

ߜ No equal sign appears after the shortcut word!
ߜ The line doesn’t end with a semicolon (it’s not a C language statement)!
ߜ You can also use escape-sequence, backslash-character things in a
defined string constant
...
Only if the string
appears many times over and over in your program is it necessary to
make it a constant
...

ߜ You can also use math and other strangeness in a defined numeric con­
stant
...

ߜ Using the #define thing isn’t required, and you’re not penalized if
you don’t use it
...
And,
you can use variables to hold your constants
...
You
won’t go to C prison
...
In fact, I recommend using it whenever you have some­
thing in your program that you figure may change
...
But are they really
constants — the opposite of variables?
No! That’s because they have the const keyword, which converts a mildmannered variable into an unyielding constant
...
The value cannot be changed or used for something else later
in the program; if you try, a “read-only variable” error pops up
...
Instead, this
statement is quite common:
const char prompt[] = “Your command:”;

This statement creates the string variable prompt and sets its contents equal
to Your command:
...


Chapter 9


How to C Numbers
In This Chapter
ᮣ Using different variables for different numbers
ᮣ Understanding the long and short of int
ᮣ Knowing your signed and unsigned variables
ᮣ Floating a number
ᮣ Double floating a number
ᮣ Formatting a huge value

P

ut on your safety goggles, my greenhorn companion! I have danced around
the flaming inferno of numbers far too long
...
Far down from the comfy safety of the int lie
numbers large and loathsome
...
Numbers lethal and toxic, but which you can also tame,
as long as you obey my gentle advice in this chapter
...
Watch your step
...
It’s known as the C Numeric Data Type Puzzle
...
This makes the frustration factor begin
rising, with the logical question “What’s a number type?”

108

Part II: Run and Scream from Variables and Math
Okay
...
” It’s a numeric data type, which is how you say
“number type” if you work at the Pentagon
...
For example, you have to know the following things
about the number:
ߜ Is it a whole number — without a fraction or decimal part?
ߜ How big is the number (as in value-large, not big-on-the-page-large)?
ߜ If the number does have a fractional part, how precise must the number
be? (Like to the thousandths, millionths, or gazillionths decimal place
...
)
I know that this stuff is all alien to you
...

ߜ The most common numeric data type is the integer
...

ߜ Keep reading
...
Table 9-1 lists them all, along with other statistical informa­
tion
...
This table is something you refer to now
and again because only the truly insane would memorize it
...
4 ∞ 1038 to
±3
...
7 ∞ 10–308 to
±1
...
If you have been reading the chapters in this book in order, you
have used int, char, and float already
...

For example, char defines a character (or string) variable, and int
defines integers
...

ߜ The range tells you how big of a number fits into the variable type
...

Other types of variables handle larger values
...

Table 9-1 isn’t that complex
...
The float and double variables are both floatingpoint, though the values held by double are larger
...
Is bad
...

Oftentimes, you need only small, whole-number values when you’re program­
ming
...
By comparison, integers are far
quicker
...


Integer types (short, long,
wide, fat, and so on)
You have to concern yourself with only two types of integers: the normal
integer — the int — and the long integer — the long
...
)
The int (rhymes with “bent”) is a whole-number value, normally ranging from
–32,768 to 32,767
...
In some versions of C, you may see this value referred to as a short or
short int
...
This type of numeric variable is referred to as a long,
or long int in some versions of C
...
int is
for smaller values; long is for larger values
...
(You can also use the %i placeholder; refer to Table 24-2 in Chap­
ter 24
...
If Soup for One were a variable, it would be an int
...


Chapter 9: How to C Numbers
ߜ In some C compilers, the ranges for int and long int are the same
...
It’s merely
technical junk; don’t memorize it or let it otherwise ruin your day
...
See the next section
...
These variables are used mostly to store
single characters (or strings), which is discussed somewhere else
...
) Oh, it’s in Chapter 10
...
They’re good only when you play
Hearts
...

When you declare a numeric variable in C, you have two choices: signed and
unsigned
...
The
standard int variable can hold values from –32,768 up to 32,767
...
(Zero is considered positive in some cults
...
This
unsigned number moves the number range all up to the positive side — no
negatives (the C language equivalent of Prozac)
...
Negative numbers aren’t allowed
...
Try that with a signed
int! Ha!
unsigned int elephants 40000;

Table 9-2 illustrates the differences between the variable types as far as the
values they can hold are concerned
...
The
secret is that everything, no matter how it looks
on the screen or in your program, is stored in
the binary tongue inside the computer
...

Binary numbers are composed of bits, or binary
digits
...
Those two
bytes contain 16 binary digits, or bits
...
) For example:
0111 0010 1100 0100

This value is written as 29,380 in decimal (the
human counting system)
...

Look at this number:

Table 9-2

0111 1111 1111 1111

It’s the value 32,767 — almost a solid bank of
ones
...
For a
signed value, a 1 in the far left position of the
number isn’t a 1 at all
...
The pre­
ceding number becomes –32,768 in binary math
...

The deal with signed and unsigned numbers all
depends on that pesky first bit in the computer’s
binary counting tongue
...

Otherwise, the first bit is just another droll bit in
the computer, happy to be a value and not a
minus sign
...

ߜ Floating-point numbers are covered in the following section
...


Chapter 9: How to C Numbers
ߜ Signed variables can be maddening and the source of frustration as far
as creepy errors are concerned
...
If that variable already holds the value
32,767, its new value (after you add 1) is –32,768
...
In that instance, you should be
using an unsigned int variable type to avoid the problem
...
Your C compiler may have a secret switch
that allows you to always create programs by using unsigned variables;
refer to the online documentation to see what it is
...

Integer variables are the workhorses in your programs, handling most of the
numeric tasks
...
That variable is the float
...
Here’s the format:
float var;

The keyword float is followed by a space or a tab, and then comes the vari­
able name, var
...

Or, you can declare a float variable and give it a value, just as you can any
other variable in C:
float var=value;

In this format, the variable var is followed by an equal sign and then a value
to be assigned to it
...
That term somehow refers to the decimal point
in the number
...
4567

An integer variable wouldn’t cut it for this number
...

When you have a decimal, you need a floating-point variable
...
With most C compilers,
you can store any number in the range ±3
...
4 × 1038
...

An undecillion is a 1 with 36 zeroes after it
...
Spock-size
value, though most numbers you use as floats are far less
...

ߜ Noninteger values are stored in float variables
...
However
...
They require
more internal storage and more PC processing time and power than inte­
gers do
...


“Hey, Carl, let’s write a floating-point
number program!”
Suppose that you and I are these huge, bulbous-headed creatures, all slimy and
green and from the planet Redmond
...
I’m Dan
...

One day, while assaulting cows in Indiana, we get into this debate:
Dan: A light-year is 5,878,000,000,000 miles long! That’s 5 trillion, 878 bil­
lion, plus change! I’m not walking that!
Carl: Nay, but it’s only a scant 483,400,000 miles from the sun to Jupiter
...

Dan: How much of a fraction?
Carl: Well, why don’t you type the following C program and have your
computer calculate the distance for you?
Dan: Wait
...
You type the program, JUPITER
...
Sheesh
...
h>
int main()
{
float lightyear=5
...
\n”,distance);
return(0);
}

Enter this program into your text editor
...
Save the file to disk as JUPITER
...


Compile the program
...


Run the program
...
000082 light years from the sun
...


ߜ You use the float keyword to declare a floating-point variable
...
878E12
...
878 should be shifted to
the right 12 times
...
)
ߜ The variable jupiter is set equal to the mean distance between Jupiter
and the sun, which is 484 million miles
...
There’s no need to mess with scientific notation here
because the compiler can eat this relatively small-size number
...
)
ߜ The distance variable contains the result of dividing the distance
between the sun and Jupiter by the length of a light-year — to find out
how many light-years Jupiter is from the sun
...

ߜ The %f placeholder is used in the printf() function to display floatingpoint values
...


115

116

Part II: Run and Scream from Variables and Math

The E notation stuff

When you deal with very large and very small numbers, the old scientific E
notation stuff crops up
...

E notation is required in C (or even in the Excel spreadsheet) when some num­
bers get incredibly huge
...
Integers don’t count
...
For example, take
the length of a light-year in miles:
5,878,000,000,000

That’s 5 trillion, 878 billion
...
The value is still the same; only the
commas — conveniently added to break up large numbers for your human
eyeballs — have been removed
...

It’s not the value that bugs the compiler — it’s the number of digits in the
number
...
Here’s the same
value in E notation, as you specify it in the JUPITER
...
878E12

Scientific, or E, notation uses a number in the following format:
x
...
xxxx is a value; it’s one digit followed by a decimal point and then more
digits
...
To find out the number’s
true size, you have to hop the decimal point in the x
...
Figure 9-1 illustrates how this concept works with the light-year value
...


5
...
78
587
...

58780
...

5878000
...

587800000
...

58780000000
...

5878000000000
...
To dis­
play the numbers in E format with printf(), you can use the %e placeholder
...
C program with %e, save
the change to disk, recompile, and run the result
...
223886e-05 light years from the sun
...
You
would translate the preceding value into the following:

...

ߜ A negative E number means that the value is very small
...

ߜ Some compilers allow you to use the %E (big E) placeholder in printf()
to display scientific-notation numbers with a big E in them
...

These types of variables can contain absolutely huge values and should be
used only when you must work with those outer-space-size values or when
you require a mathematical operation that must be precise
...
Double comes
from the term double precision, which means that the numbers are twice as
accurate as floats, which are also known as single-precision numbers
...
Keep in mind that the computer
uses only ones and zeroes to store information
...
For
non-integers, it means that some tomfoolery must take place
...

As an example, gawk at this number:
123
...
But if you define that value as a float variable
in C, the computer can store it only as a single-precision value
...
The rest — it makes them up! To wit:
123
...
The rest — eh? After the 8, the value gets
screwy
...
Double precision can be accurate to
maybe 12 or 16 decimal places (but after that, it begins acting goofy as well)
...
After
about eight digits or so, the rest of the output is meaningless
...
It still has its prob­
lems, but it’s more precise than the float
...

ߜ If you ever print a value — 123
...
456001, that extra 001 is the lack of precision the
computer has when it’s dealing with floating-point numbers
...


Chapter 9: How to C Numbers
ߜ Being accurate to eight digits is more than enough for most noninteger
calculations
...
(I know that NASA reads these books intently
...

ߜ The greater the precision, the longer it takes the computer to deal with
the numbers
...


Formatting Your Zeroes
and Decimal Places
Floating-point values can sure look gross when they’re displayed by using the
%f in the printf() function
...
Now you have to plug your nose and plunge
a little deeper into the murky waters of printf() formatting
...

Between the % and the f, you can insert some special formatting characters
...

The following few examples show you how to trim up your numbers with
printf() and avoid the cavalcade of zeroes that appears sometimes when

you’re dealing with floats and doubles
...
It’s ideal for displaying dollar amounts
...
9500 displayed as a price — which doesn’t appease your customer’s
sense of thrift any
...
2f

If you need to display more decimal places, specify that number after the dot:
%
...
If the value isn’t that small, zeroes pad out the four deci­
mal places
...

Rather than leading zeroes, the number is padded on the left with spaces
...


This line begins with two spaces, or is indented two spaces, depending on how
you look at it
...
000000

In that case, you can trim up the number by using either %
...

ߜ An alternative to messing with numbers and other characters between
the % and little f is to use the %e placeholder
...

ߜ Then there’s the %g placeholder
...

Yes, I know that this chapter is short on examples
...

So there
...
It’s
definitely more fun
...
This certainly opens the floodgates of creativity over pounding the
sand with numbers
...
In this chapter, it’s only single characters you have to worry about
...

And I think, though I’m not certain, that it’s pronounced “care” and not “char,”
as in “charred beyond all recognition
...
Unlike a string, the single-character variable holds only one
character — no more
...

The string variable is merely several padded cells one after the other — like
an asylum
...
Here’s the format:
char var;
char is written in lowercase, followed by a space and then var, the name of

the variable to be created
...
For
example, the extended ASCII characters used
on most PCs — which include the line-drawing
characters, math symbols, and some foreign
characters — require some extra effort to stuff
into character variables
...
Follow these steps:
1
...

2
...
(That’s why
hexadecimal values are usually shown in
the ASCII tables and charts
...
Specify that hex value, which is two digits
long, after the \x escape sequence
...
Remember to enclose the entire escape
sequence — four characters long — in
single quotes
...
That character’s
secret code number is 156
...
You can see that the hexadecimal value is 9C
...
) So you specify the
following escape sequence in your program:
‘\x9C’

Notice that it’s enclosed in single quotes
...
When the escape sequence is
assigned to a character variable, the C compiler
takes the preceding number and converts it into
a character — the £ — which sits snugly until
needed
...
The name of the variable you’re creating, var, is
followed by an equal sign and then a character in single quotes
...


Inside the single quotes is a single character, which is assigned to the vari­
able var
...
(See Table 24-1 in Chapter 24 for the full list
of escape sequences; also see the nearby sidebar, “Typing those hard-toreach characters
...
By using miracles of the C language not yet known, you
can compare that character with other characters and make your programs
do wondrous things
...
Oh, it can be fun
...
It’s a must!
Some characters, you can’t really type at the keyboard
...

ߜ Single-character variables are created by using the char keyword
...


123

124

Part II: Run and Scream from Variables and Math
ߜ If you predefine the variable’s value with a character, enclose that char­
acter in single quotes
...

ߜ You can assign almost any character value to the character variable
...

ߜ Information about creating string variables is presented in Chapter 4
...


Stuffing characters into
character variables
You can assign a character variable a value in one of several ways
...
If key is a character variable,
for example, you can place the character ‘T’ in it with this statement:
key=’T’;

The T, which must be in single quotes, ladies and gentlemen, slides through
the equal sign and into the key variable’s single-character holding bin
...
(I assume that key was defined as a character
variable by using the char key; statement, earlier in the program
...
As long as it’s only one charac­
ter long, you’re hunky-dory
...
Suppose that both old and new are charac­
ter variables
...
After the preceding statement, both variables hold the same
character
...
)
ߜ You can assign single characters to single-character variables
...

ߜ You still cannot use the equal sign to put a string of text into a string
variable
...
It just can’t be done
...
Both read text from the keyboard, usually
as full sentences
...
That value is stored in the char variable key, which you
can assume was already declared earlier in the program
...
h>
int main()
{
char key;
puts(“Type your favorite keyboard character:”);
scanf(“%c”,&key);
printf(“Your favorite character is %c!\n”,key);
return(0);
}

Carefully enter this source code into your editor
...
C
...
Here’s the sample output:
Type your favorite keyboard character:

Press a key, such as m (or whatever your favorite is), and then press the Enter
key
...

ߜ Yes, you have to press the Enter key to finish your input — that’s the way
the scanf() function works
...


125

126

Part II: Run and Scream from Variables and Math

The getchar() function

Fortunately, you’re not stuck with scanf() for reading in individual keys from
the keyboard
...
Here’s the
format:
var=getchar();

var is a character variable
...
var is followed by an equal sign and then getchar and two parenthe­
ses hugging nothing
...

The getchar() function causes your program to pause and wait for a key to
be typed at the keyboard
...
Sits and waits
...
Wait
...
Wait
...

The following is the update to the FAVKEY1
...
h>
int main()
{
char key;
puts(“Type your favorite keyboard character:”);
key=getchar();
printf(“Your favorite character is %c!\n”,key);
return(0);
}

Edit the source code for FAVKEY1
...
Save the new file to disk as
FAVKEY2
...
Compile and run!
The output is the same as for the first version of the program; and you still
have to press the Enter key to enter your favorite key value
...
That’s just the way getchar() works
...
)
ߜ There are ways to read the keyboard more interactively, where pressing
the Enter key isn’t required
...


Chapter 10: Cook That C Variable Charred, Please

The putchar() function

The putchar() function, pronounced “püt-care,” for “put character,” is the
opposite of the getchar() function; getchar() reads in a character from
the keyboard, and putchar() displays a character on the screen
...

The following program shows how putchar() can be put to use in tossing up
characters on the screen:
#include ...
C
...
Compile
and run:
Press Enter
...
Then:
Hello!

Note that getchar() is used here merely to read the Enter key press; any value
returned by getchar() isn’t stored
...

That’s perfectly okay
...
It’s a rather silly
use of putchar(), but it works
...

ߜ You can also specify a character as an escape sequence or a code value
with putchar() (see the next section)
...
That’s
all well and good, and it gets you an A on the quiz
...

The horrible truth is that a single-character variable is really a type of integer
...
The reason that it isn’t obvious
is that treating a char as an integer is really a secondary function of the singlecharacter variable
...
But they can be used as integers
...

The basic unit of storage in a computer is the byte
...
Each one of those bytes can be looked at as storing a single
character of information
...

Without boring you with the details, know that a byte is capable of storing a
value, from 0 to 255
...
Because a character is a byte, the char
can also be used to store those tiny integer values
...
It does, however, know the difference between 65 and 66
...
The letter
B is code 66
...
The
coding scheme is referred to as ASCII, and a list of the codes and characters
is in Appendix B
...
Internally, the computer sees only the 65 and, lo,
it’s happy
...
That
satisfies you and me, supposing that an A is what we want
...
The truth
is, they are integers
...
The following
program, WHICH
...
The trick with WHICH
...
Such duality! Can
you cope?
#include ...
\n”,key);
printf(“Its ASCII value is %d
...
C
...
C
...

Run the final program
...

Its ASCII value is 65
...
This placeholder tells printf() to display the variable as a char­
acter
...
That one tells printf() to display the variable as an integer
value — which it does
...

ߜ ASCII code values range from 0 to 127
...
Those characters aren’t standard on all computers, though
they’re pretty consistent on Windows PCs
...

ߜ Appendix B lists all the ASCII characters and their values
...
What’s being compared is really the character’s code
value, not its aesthetics
...


he programs illustrated in the first two parts of this
book have been top-down
...
They make no
deviations and have no change in the pattern, no creativ­
ity, no choice
...

To really make a program run amok, you can place a deci­
sion machine inside of it
...
” It’s not a choice that the computer
makes; the computer is dumb
...

In addition to making decisions, the computer is good at
doing things over and over — without complaining! Com­
bine decision-making with this love of repetition, and pretty
soon you have programs that spin off into alternative uni­
verses, taking control of the computer with them! It’s runamok time!

Chapter 11


C More Math and the Sacred

Order of Precedence

In This Chapter
ᮣ Reviewing the C math operators
ᮣ Incrementing variables
ᮣ Understanding the order of precedence
ᮣ Introducing My Dear Aunt Sally
ᮣ Using parentheses to control your math

B

eware ye the dreadful math chapter! Bwaa-ha-ha!


Math is so terrifying to some people that I’m surprised there isn’t some

math-themed horror picture, or at least a ride at Disneyland
...
Ghosts
...
Disneyland needs math in order to terrify and thrill children

of all ages
...
But I digress
...
Don’t panic!

The computer does all the work
...
And, if you do it wrong,

the C compiler tells you and you can start over
...
No

recriminations
...



An All-Too-Brief Review of the Basic
C Mathematical Operators
Table 11-1 shows the basic C mathematical operators (or it could be arith­
metic operators — whatever)
...


134

Part III: Giving Your Programs the Ability to Run Amok
Table 11-1

C’s Mathematical Doodads

Operator
or Symbol

What You
Expect

As Pronounced
by Sixth Graders

Task

+

+

“Plus”

Addition

-



“Minus”

Subtraction

*

×

“Times”

Multiplication

/

÷

“Divided by”

Division

You use the symbols to do the following types of math operations:
ߜ Work with values directly:
total = 6 + 194;

The integer variable total contains the result of adding 6 and 194
...
The math is worked from left to right by the C compiler
...

ߜ Work with values and variables:
score = points*10;

The variable score is set equal to the value of the variable points
times 10
...
54;

The variable height_in_cm is set equal to the value returned by the
atoi function times 2
...
The atoi() function manipulates the variable
height_in_inches (which is probably a string input from the keyboard)
...
The result is then transferred to the variable sitting on the left
side of the equal sign
...
As an example, I present the HEIGHT
...
This program asks you to enter your height in inches and then
spits back the result in centimeters
...
But, bear with me for a few pages and have some fun with it
...
h>
#include ...
54;
printf(“You are %
...
\n”,height_in_cm);
return(0);
}

Be careful with what you type; some long variable names are in there
...
(I mention it because I tried to compile the program
with that spelling mistake — not once, but twice!) Save the file to disk as
HEIGHT
...

Compile the program
...
Fix them
if they crop up
...
Your output looks something like this:
Enter your height in inches:60
You are 152
...


If you’re 60 inches tall (5 feet exactly), that’s equal to 152
...
The program is
good at converting almost any length in inches to its corresponding length in
centimeters
...
It has e before i
...
(It’s your number-one typo possibility if
you get a syntax error in the program
...
And, it’s atoi(), not atio() (another reason, though
invalid, to hate English spelling)
...
Then that value is multiplied by

2
...
(The asterisk is used for multiplication
...

ߜ The value 2
...

height_in_inches is an integer because that’s the type of value the
atoi() function returns
...
That’s why the height_in_cm variable is a float
...
54 centimeters in
...
However, if you’re on
Jeopardy! and the Final Jeopardy answer is 2
...
(By the way, an easy mnemonic device for remembering how many
centimeters are in an inch is to scream “two-point-five-four centimeters
per inch” at the top of your lungs 30 times
...
39 inches
...


Unethical alterations to the old
“how tall are you” program
Though I’m not standing behind you, I can clearly see the HEIGHT
...
Good
...
54*1
...
54 and before the semicolon, insert *1
...
This increases your height by five-hundredths of a centimeter for each
centimeter you have in height
...

Then run it again:
Enter your height in inches:60
You are 160
...


That may not mean much to you
...
If so, you can
tell him or her that, according to a program run on your computer, you’re

Chapter 11: C More Math and the Sacred Order of Precedence
160
...
That means nothing to an American, but it means that
you’re three whole inches taller in France
...
69 centimeters tall
...
69 centimeters tall — or 6'11⁄ 2" tall! They’ll swoon!
And now, the confession:
The purpose of this discussion is not to tell you how to cheat when you’re
programming a computer, nor is there any value in deceiving the French
...
However, it
does show you the following:
height_in_cm = atoi(height_in_inches)*2
...
05;

The variable height_in_cm is equal to the result of three mathematical oper­
ations: First, an integer is produced based on the value of the string variable
height_in_inches
...
54, and the result is multiplied
again by 1
...

Having a long mathematical formula is perfectly okay in C
...
To ensure that you always get the
result you want, however, you must pay special attention to something called
the order of precedence
...

ߜ An equation in C can have more than two items
...
The items must all be on the right, after
the equal sign
...
05 (five-hundredths, or 5 percent), the
number must be multiplied by 1
...
If you just multiply it by
...
Instead, you want to increase it by 5 percent,
so you multiply it by 105 percent, or 1
...
I stumbled on this knowledge
accidentally, by the way
...
You
move something up a notch by incrementing it — for example, shifting from
first to second, racking up another point in Gackle Blaster, or increasing your
compensation by a dollar an hour
...


137

138

Part III: Giving Your Programs the Ability to Run Amok
Increasing the value of a variable in C happens all the time
...
It looks funny, but it works
...
Then i+1 (which is 3 + 1) equals 4
...
The preceding statement increments the value of the i
variable by 1
...
For example:
i=i+6;

This equation increments the value of the i variable by 6
...
” Then again,
true purists wouldn’t put any dressing on their salad, so what do they know
anyway?)
ߜ To add 1 to a variable — i, in this instance — you use the following C
language mathematical-statement thing:
i=i+1;

This is known as incrementation
...
Different subject
...

ߜ Incrementation — i=i+1 — works because C figures out what’s on the
right side of the equal sign first
...
Then it replaces the
original value of the i variable
...


Unhappily incrementing your weight

The following program is LARDO
...
You enter what you weigh, and then
LARDO calculates your newfound bulk as you consume your holiday feast:

Chapter 11: C More Math and the Sacred Order of Precedence
#include ...
h>
int main()
{
char weight[4];
int w;
printf(“Enter your weight:”);
gets(weight);
w=atoi(weight);
printf(“Here is what you weigh now: %d\n”,w);
w=w+1;
printf(“Your weight after the potatoes: %d\n”,w);
w=w+1;
printf(“Here you are after the mutton: %d\n”,w);
w=w+8;
printf(“And your weight after dessert: %d pounds!\n”,w);
printf(“Lardo!\n”);
return(0);
}

Type the preceding source code into your text editor
...
The final equation, w=w+8, adds eight to the value of
the w variable
...
Save the
file to disk as LARDO
...

Compile LARDO
...
Fix any errors, if need be
...
It’s called incrementation
...
)
ߜ Yeah, 175 pounds! I’m sure that you typed an equally modest value
rather than something more representative of your true girth
...
The
only problem at that point is drawing the Community Chest card that pro­
claims the following:
You are assessed for street repairs — $40 per house, $115 per hotel
...

It’s a terrible thing to do to one’s brain in the middle of a Monopoly game
...
C:
#include ...
h>
int main()
{
int houses, hotels, total;
char temp[4];
printf(“Enter the number of houses:”);
gets(temp);
houses=atoi(temp);
printf(“Enter the number of hotels:”);
gets(temp);
hotels=atoi(temp);
total=houses*40+hotels*115;
printf(“You owe the bank $%d
...
Double-check
your semicolons, parentheses, and quotes
...
C
...
Then run the program
...
Here’s what your output looks like:
Enter the number of houses:9
Enter the number of hotels:3
You owe the bank $705
...
All you need is for
some poor sap to land on St
...

ߜ Notice how the temp variable is used to hold and help convert two dif­
ferent strings into numbers? This example illustrates how variables can
change and, well, be variable
...

ߜ You may think, and rightly so, that the total displayed by the program
should be a float variable
...
00 rather than $705
...
Keep in mind that integers are faster, which is especially
apparent in larger programs
...
The fact that the theater is on fire, for
example, takes precedence over the fact that you’ll miss the second act if you
leave in a hurry
...
It refers to which of the mathematical operators has prior­
ity over the others
...
In C, other
mathematical operations are done before addition
...


A problem from the pages

of the dentistry final exam

Witness with your own eyes the following long and complex mathematical
equation that may one day slink into one of your C programs:
answer = 100 + 5 * 2 - 60 / 3;

This question is one of those tough math questions from the dentistry final
exam
...
The
preceding problem isn’t really a problem for you, though
...
But what is it?

141

142

Part III: Giving Your Programs the Ability to Run Amok
Is the answer 50? One hundred plus 5 is 105; times 2 is 210; minus 60 is 150;
divided by 3 is 50
...
This all has to do with My
Dear Aunt Sally and the order of precedence
...
C, which you can type to prove that the
answer is 90 and not 50:
#include ...
Compile it
...
It’s
a printf() statement, with only %d in double quotes
...

Run the program
...
Not knowing
how the C compiler works out its math means that you may not get the
answer you want
...

ߜ When the DENTIST
...
The result is then passed
over to the fill-in-the-blanks %d and is displayed on the screen
...
C to declare the answer integer vari­
able, assign the value to that variable, and then use printf() to display
the variable’s contents
...
That would be too long of a program
...
The printf() state­
ment in DENTIST
...


What’s up, Sally?

My Dear Aunt Sally is a mnemonic device, or “a silly thing we say to remem­
ber something we would forget otherwise, which isn’t saying much because
we nearly always forget our own phone number and family birthdays
...

The compiler scopes out an entire equation — the whole line — and does the
multiplication first and then the division and then the addition and subtrac­
tion
...
Figure 11-1 illustrates how
the mathematical example in the preceding section figures out to be 90
...


10

10

-

20;

-

20;

answer =

110

answer =

90;

Here’s another puzzle:
answer = 10 + 20 * 30 / 40;

In this statement, the multiplication happens first and then the division and
then the addition
...

When the computer is finished counting its thumbs and the preceding state­
ment is resolved, the answer variable contains the value 25
...
C program and replacing the math that’s already there,
in the preceding math equation
...
Or, just trust me and let it go at that
...
Multiplication (*), division (/), addition (+), and sub­
traction (–) are done in that order in the C language’s long mathematical
equations
...

ߜ The ASSESSED
...
The last step is to add the two
...


The confounding magic-pellets problem

I hated those math-class story problems when I was a kid
...
In
any event, here I am, in my adulthood, making up something like the following:
Suppose that you have 100 of these magic pellets
...
After a day, you have 200
...
If so, how many magic pellets would you have
the next day?
Don’t bother stewing over the problem
...
In your head, you can figure that 100 minus 25 is 75
...
But in C, this just wouldn’t
work; the order of precedence (that Sally person) would multiply 25 by 2
first
...
What a gyp!
The following C program, PELLETS
...
This program is a somewhat
more complex version of the basic DENTIST
...
h>
int main()
{
int total;
total=100-25*2;
printf(“Tomorrow you will have %d magic
pellets
...
Double-check everything
...
C
...
C
...

Run the PELLETS program
...


Uh-huh
...
Your computer program, diligently
entered, tells you that there are 50 pellets, when tomorrow you will really
have 150
...
In the
PELLETS
...
The way that works is by
using parentheses
...
She’s insistent
...
In the PELLETS
...
Anyone who reads the problem knows that you must subtract
25 from 100 first and then multiply what’s left by 2
...

You can circumvent the order of precedence by using parentheses
...

To fix the PELLETS
...
So, at once, 25 is sub­
tracted by 100, to equal 75
...

I beg of you to make the preceding change to Line 7 in your PELLETS
...
Stick the left parenthesis before 100, and insert the right one after 25
...
The result
should please you:
Tomorrow you will have 150 magic pellets
...
It doesn’t
matter whether it’s addition, subtraction — whatever
...

ߜ Inside the parentheses, the math is still worked from left to right
...
It’s
just that whatever is in the parentheses is done before whatever is out­
side
...
Work inside the parentheses first
...
Multiplication and division first, and addition and subtraction
second
...
Work from left to right
...
And, if you don’t use spreadsheets,
then, hey — you have read about something in a C book that you can
apply to your spreadsheeting
...

ߜ Yeah, you can even put parentheses inside parentheses
...

ߜ It doesn’t matter where the parentheses are in the math equation; what’s
in them is always done first
...
The result, 75, is then
multiplied by 2
...


Chapter 12


C the Mighty if Command
In This Chapter
ᮣ Using the if statement
ᮣ Comparing values with if
ᮣ Formatting the if statements
ᮣ Handling exceptions with else
ᮣ Making multiple decisions

O

kay, if isn’t a command
...
It’s the program that
decides what to do based on the results of the comparison
...

Keep in mind that the computer doesn’t decide what to do
...
It’s kind of like instructing small chil­
dren to do something, though with the computer, it always does exactly what
you tell it to and never pauses eternally in front of the TV set or wedges a Big
Hunk into the sofa
...

The idea behind the if command is to have the computer handle some pre­
dictable yet unknown event: A choice is made from a menu; the little man in
some game opens the door with the hydra behind it; or the user types some­
thing goofy
...


148

Part III: Giving Your Programs the Ability to Run Amok
The if keyword allows you to put these types of decisions into your pro­
grams
...
For example:
ߜ If the contents of variable X are greater than variable Y, scream like

they’re twisting your nose
...

ߜ If it ain’t broke, don’t fix it
...

All these examples show important decisions, similar to those you can make
in your C programs by using the if keyword
...
Here are more accurate examples:
ߜ If the value of variable A is equal to the value of variable B

ߜ If the contents of variable ch are less than 132

ߜ If the value of variable zed is greater than 1,000,000

These examples are really simple, scales-of-justice evaluations of variables
and values
...

ߜ if is a keyword in the C programming language
...

ߜ if decides what to do based on a comparison of (usually) two items
...
If not, that part of the program
doesn’t run
...
I wrote this topic down in my notes, probably because it’s in
some other C reference I have read at some time or another
...
Impress your friends with that term if you can remember it
...
(That’s what I do
...
C, one of many silly computer guess-thenumber programs you write when you find out how to program
...
They would probably drop dead if we could beam a Sony PlayStation
back through time
...
C does is to ask for a number, from 0 through 9
...
Then, using the magic of the if statement, the com­
puter tells you whether the number you entered is less than 5
...

Enter the following source code into your text editor
...
Better
double-double-check your typing
...
h>
#include ...
C
...
C
...


Then recompile
...
You see these displayed:

I am your computer genie!
Enter a number from 0 to 9:

Type a number, somewhere in the range of 0 through 9
...
Press Enter and you see:
That number is less than 5!
The genie knows all, sees all!

149

150

Part III: Giving Your Programs the Ability to Run Amok
ߜ The #include ...

ߜ The if command is followed by parentheses, which contain the compar­
ison that the if keyword tests
...
The < symbol between them means “less than
...
” If this is true, the cluster
of statements following the if keyword is executed
...

ߜ Remember the < — less than — from school? Good!
ߜ Notice that the if test isn’t followed by a semicolon! Instead, it’s fol­
lowed by a statement enclosed in curly braces
...

ߜ If you see only the line The genie knows all, sees all!, you proba­
bly typed a number greater than 4 (which includes 5 and higher)
...
If the
value is less than 5, That number is less than 5! is displayed
...

ߜ No, the computer genie doesn’t know all and see all if you type a number
5 or greater
...
Also notice how

they’re indented
...
The if keyword has a
unique format, with plenty of options and room for goofing things up
...

The if keyword is used to make decisions in your programs
...
If the result is true, the rest of the if statement is executed
...

The if statement is a statement “block” that can look like this:
if(comparison)
{
statement;
[statement;
...



True

if(chins>3)
{
printf("Where is your neck?");
}
printf("something else");

if is followed by a set of parentheses in which a comparison is made
...

What’s being compared is usually the value of a variable against a constant
value, or two variables against each other
...
)

If the result of the comparison is true, the statement (or group of statements)
between the curly braces is executed
...

Yes, the curly braces that follow if can contain more than one statement
...
All are enclosed in the
curly braces
...
It shows you which
statements “belong” to if
...


Table 12-1

Operators Used in if Comparisons

Comparison

Meaning or Pronunciation

“True” Examples

<

Less than

1<5
8<9

==

Equal to

5 == 5
0 == 0
(continued)

151

152

Part III: Giving Your Programs the Ability to Run Amok
Table 12-1 (continued)
Comparison

Meaning or Pronunciation

“True” Examples

>

Greater than

8>5
10 > 0

<=

Less than or equal to

4 <= 5
8 <= 8

>=

Greater than or equal to

9 >= 5
2 >= 2

!=

Not equal to

1 != 0
4 != 3
...
What’s
being compared is the value of the numeric variable number and the constant
value 5
...
” Is number less than 5? If so, the state­
ment in curly braces is executed
...

Consider these modifications:
if(number==5)
{
printf(“That number is 5!\n”);
}

Now, the comparison is number==5? (Is the number that is entered equal to
five?) If it is, the printf() statement displays That number is 5!
These changes compare the value of number with 5 again:
if(number>=5)
{
printf(“That number is more than 4!\n”);
}

Chapter 12: C the Mighty if Command
This time, the test is greater than or equal to: Is the number that is entered 5
or more than 5? If the number is greater than or equal to 5, it must be more
than 4, and the printf() statement goes on to display that important info on
the screen
...
C program doesn’t change the if
comparison, as in the previous examples
...

Advanced C programs may have lots of stuff in there; as long as it’s between
the curly braces, it’s executed only if the comparison is true
...
)
ߜ The comparison that if makes is usually between a variable and a value
...

ߜ if cannot compare strings
...

ߜ Less than and greater than and their ilk should be familiar to you from
basic math
...

ߜ The symbols for less than or equal to and greater than or equal to always
appear that way: <= and >=
...

ߜ The symbol for “not” in C is the exclamation point
...
” What is !TRUE (not-true) is FALSE
...
” No, I do ! want to eat those soggy zucchini chips
...
I think of it this way: When you build an if
statement to see whether two things are equal, you think in your head
“is equal” rather than “equals
...
” If you think “equals,” you have a tendency to use only one
equal sign — which is very wrong
...
The nearby Technical Stuff sidebar attempts
to explain why
...
The final curly brace signals to
the compiler that the if statement has ended
...


A question of formatting the if statement

The if statement is your first “complex” C language statement
...

Though you probably have seen the if statement used only with curly
braces, it can also be displayed as a traditional C language statement
...
To wit:
if(number==5) printf(“That number is 5!\n”);

This line looks more like a C language statement
...

Everything still works the same; if the value of the number variable is equal
to 5, the printf() statement is executed
...

Although all this is legal and you aren’t shunned in the C programming com­
munity for using it, I recommend using curly braces with your if statements
until you feel comfortable reading the C language
...

What the C compiler does is to figure out what
you have put between the parentheses
...


No, you need two equal signs for that
...
It’s the same as

For a comparison using <, >, ==, or any of the
horde in Table 12-1, the compiler figures out
whether the comparison is true or false
...
For example:

The C compiler obeys this instruction, stuffing 1
into the input variable
...
It tells the if keyword, and the cluster of
statements that belong to the if statement are
then executed
...


The final solution to the
income-tax problem
I have devised what I think is the fairest and most obviously well-intentioned
way to decide who must pay the most in income taxes
...
Yessir, it would be
hard to dodge this one
...
You pay taxes based on
either your height or the temperature outside, multiplied by your favorite
number and then 10
...
To figure out which number is higher, the program TAXES
...
It’s done twice — once for the height
value and again for the temperature outside:

155

156

Part III: Giving Your Programs the Ability to Run Amok
#include ...
h>
int main()
{
int tax1,tax2;
char height[4],temp[4],favnum[5];
printf(“Enter your height in inches:”);
gets(height);
printf(“What temperature is it outside?”);
gets(temp);
printf(“Enter your favorite number:”);
gets(favnum);
tax1 = atoi(height) * atoi(favnum);
tax2 = atoi(temp) * atoi(favnum);
if(tax1>tax2)
{
printf(“You owe $%d in taxes
...
\n”,tax2*10);
}
return(0);
}

This program is one of the longer ones in this book
...
It has nothing new in it, but it covers almost all the informa­
tion I present in the first several chapters
...

Save the file to disk as TAXES
...

Compile TAXES
...
Fix any errors you see
...
Five feet is 60 inches; six feet is 72 inches
...
Press Enter
...

That’s Fahrenheit, by the way
...

If you do, the IRS will hunt you down like a delinquent country music star and
make you pay, pay, pay
...
Mine is 11
...

If I type 72 (my height), 18, and 11, for example, I see the following result, due
April 15:
You owe $7920 in taxes
...
I guess I need a smaller
favorite number
...
” This catches
the case when your height is equal to the temperature
...
The
first if comparison, “tax1 is greater than tax2,” fails because both are
equal
...

ߜ If you enter zero as your favorite number, the program doesn’t say that
you owe any tax
...
Sad, but true
...
Instead, hold on to the TAXES
...
If it’s already in your text
editor, great
...

The last part of the TAXES
...
The
second if statement, which should be near Line 23 in your editor, really isn’t
necessary
...

Change Line 23 in the TAXES
...
It looks like this now:
if(tax2>=tax1)

Edit that line: Delete the if keyword and the comparison in parentheses and
replace it with this:
else

That’s it — just else by itself
...


157

158

Part III: Giving Your Programs the Ability to Run Amok
Save the file back to disk
...
C
...
The output is the same because the
program hasn’t changed (and assuming that it hasn’t gotten any warmer and
you haven’t grown any taller in the past few moments)
...

ߜ The else keyword is a second, optional part of an if cluster of state­
ments
...

ߜ Or else what?
ߜ Alas, if you enter the same values as in the old program, you still owe
the same bundle to Uncle Sam
...
By itself, the if keyword can handle minor deci­
sions and execute special instructions if the conditions are just so
...
Figure 12-2 illustrates how this can happen
...


True

if(chins>3)
{
printf("Where is your neck?");
}
else
{
printf("My, but what a slender neck
...
But, if the comparison is false, the statements belonging to the
else are executed
...
Then, after going its own way, the statement following the
else’s final curly brace is executed, like this: “You guys go around the left
side of the barn, we’ll go around the right, and we’ll meet you on the other
side
...
The keyword holds its own
group of statements to be executed (okay, “obeyed”) when the if compari­
son isn’t true
...
If it’s a true
comparison — no foolin’ — the statements that appear in curly braces
right after the if statement are executed
...
One way or another, one group of statements is executed and
the other isn’t
...
It isn’t
followed by a semicolon
...
The
curly braces enclose one or more statements to be run when the comparison
that if makes isn’t true
...

The statements belonging to the else keyword are executed when the condi­
tion that the if keyword evaluates is false
...


159

160

Part III: Giving Your Programs the Ability to Run Amok
Table 12-2

if Comparisons and Their Opposites

if Comparison

else Statement Executed By This Condition

<

>= (Greater than or equal to)

==

!=

>

<= (Less than or equal to)

<=

>

(Greater than)

>=

<

(Less than)

!=

== (Is equal to)

(Not equal to)

ߜ I don’t know about you, but I think that all those symbols in Table 12-2
would certainly make an interesting rug pattern
...

ߜ Both if and else can have more than one statement enclosed in their
curly braces
...

ߜ To execute means to run
...
Each line is
executed one after the other unless statements like if and else are
encountered
...

ߜ When your program doesn’t require an either-or decision, you don’t
have to use else
...
But, suppose that you’re writing a program that displays an error
message when something doesn’t work
...

ߜ If you’re the speaker of another programming tongue, notice that the C
language has no end-else word in it
...
The final curly brace signals the end of the else state­
ment, just as it does with if
...
The if keyword helps if you
need to test for only one condition
...
And, if it’s
true, a group of statements is executed
...
(After
the if’s group of statements is executed, the program continues as before
...
Just as you can abbre­
viate an if statement to one line, you can also
abbreviate else
...
\n”,tax1*10);
}
else
{
printf(“You owe $%i in
taxes
...
C program: the if-else struc­
ture
...
\n”,tax1*10);
else
printf(“You owe $%i in
taxes
...
The
following format is also possible, though it
makes the program hard to read:

if(tax1>tax2) printf(“You owe
$%i in taxes
...
\n”,tax2*10);

Everything is scrunched up on two lines; the if
statement has its own line, and the else has its
own line
...
But, look-it
...

You can do this trick — eliminating the curly
braces — whenever only one statement
appears with an if or else keyword
...
That’s
why I recommend them all the time: No sense
risking prison over brevity
...
\n”,tax1*10);
else
{
printf(“You owe $%i in
taxes
...


Either-or conditions are the daily bread of the if-else duo
...

What about “one, two, or the third” types of decisions? For them, you need
the miraculous and overly versatile else-if combination
...


161

162

Part III: Giving Your Programs the Ability to Run Amok
The following program is a modification of the GENIE1
...
This time, the else-if combination is used to
allow the computer genie to accurately report whether the number is less
than 5, equal to 5, or greater than 5:
#include ...
h>
int main()
{
char num[2];
int number;
printf(“I am your computer genie!\n”);
printf(“Enter a number from 0 to 9:”);
gets(num);
number=atoi(num);
if(number<5)
{
printf(“That number is less than 5!\n”);
}
else if(number==5)
{
printf(“You typed in 5!\n”);
}
else
{
printf(“That number is more than 5!\n”);
}
printf(“The genie knows all, sees all!\n”);
return(0);
}

Start working on this source code by loading the GENIE1
...
Make modifications so that
the latter part of the program looks like the new, GENIE2
...

Watch your indenting
...
Pay attention to where semicolons go and where they
don’t go
...
C
...
C
...


Chapter 12: C the Mighty if Command
Run the final result and see how much more clairvoyant the computer genie
has become
...

The second if comes right after else and a space
...

ߜ In GENIE2
...
Two equal signs are used
for this comparison
...
How­
ever, the C language has a better solution in the select-case structure
...


Bonus program! The really,
really smart genie
A solution always exists
...
But, why bother with if at all?
Okay, the if keyword is the subject of this section, along with if-else and
else-if and so on
...
C doesn’t use
if at all
...
h>
int main()
{
char num;
printf(“I am your computer genie!\n”);
printf(“Enter a number from 0 to 9:”);
num = getchar();
printf(“You typed in %c!\n”,num);
printf(“The genie knows all, sees all!\n”);
return(0);
}

163

164

Part III: Giving Your Programs the Ability to Run Amok
You can create this source code by editing either GENIE1
...
C
...
C
...
Fix any errors that you (hopefully) don’t get
...
Hey! That genie
knows exactly what you typed! I wonder how that happened? It must be your
deftness with the C language
...
C? It doesn’t make a decision
...
The purpose
behind if, else, and the others is that they allow you to make a deci­
sion in your program
...


Chapter 13


What If C==C?
In This Chapter
ᮣ Comparing characters with if
ᮣ Understanding standard input
ᮣ Fixing the flaws of getchar()
ᮣ Making a yes-or-no decision

A

pologies are in order for the preceding chapter
...
Computer
programs aren’t all about numbers, and the judgment that the if keyword
makes isn’t limited to comparing dollar amounts, ecliptic orbits, subatomic
particle masses, or calories in various fudgy cookie snacks
...
That should finally answer
the mystery of whether the T is “greater than” the S and why the dollar sign is
less than the minus sign
...


The World of if without Values

I ask you: How can one compare two letters of the alphabet? Truly, this sub­
ject is right up there with “How many angels can dance on the head of a pin?”
and “Would it be a traditional dance, gavotte, rock, or perhaps heavenly
hokey-pokey?”
Yet, comparing letters is a necessary task
...
That’s done by using
the handy if keyword
...
The
comparison that if makes is to see whether the content of that variable is
equal to (two equal signs) the letter A, which is enclosed in single quotes
...
Did the user type an A?
ߜ To compare a single-character variable with a character — letter, number,
or symbol — you must enclose that character in single quotes
...

ߜ When if tests to see whether two things are equal, two equal signs are
used
...

ߜ When you compare a variable — numeric or single character — to a con­
stant, the variable always comes first in the comparison
...
9E3 angels can dance on the head of a pin, given the rela­
tive size of the pin and the size of the angels and whether they’re dancing
all at once or taking turns
...
This is one of those weird instances when
the single-character variable acts more like an integer than a letter, num­
ber, or symbol
...
T comes after S
...


Computers and math (do I even have
to remind you to skip this stuff?)
Sad to say, too much about computers does deal
with math
...
After all, working with numbers is called
computing, which comes from the ancient Latin
term computare
...

Another word for compute is reckon, which is
popular in the South as “I reck’n
...
” Computers
reckon
...


Chapter 13: What If C==C?
To solve this great mystery of life, I list next the source code for a program,
GREATER
...
It asks you to enter two single characters
...
The greater of the two
is then displayed
...
h>
int main()
{
char a,b;
printf(“Which character is greater?\n”);
printf(“Type a single character:”);
a=getchar();
printf(“Type another character:”);
b=getchar();
if(a > b)
{
printf(“‘%c’ is greater than ‘%c’!\n”,a,b);
}
else if (b > a)
{
printf(“‘%c’ is greater than ‘%c’!\n”,b,a);
}
else
{
printf(“Next time, don’t type the same character
twice
...
C into your editor
...

Save the file to disk as GREATER
...

Compile GREATER
...

Run the final program
...
Press Enter after typing the
character
...
Right in the middle of the chapter that talks about compar­
ing single-character variables, I have to totally pick up the cat and talk about
something else vital in C programming: properly reading single characters from
the keyboard
...
That’s what the getchar() function returns, but it’s
not what the function does
...
It grabs the first char­
acter you type and stores it, but afterward it sits and waits for you to type
something that signals “the end
...
The second is
the EOF, or end-of-file, character
...
In the
Unix-like operating systems, it’s Ctrl+D
...
When it asks for
input, type 123 and then press the Enter key
...

The getchar() function reads standard input
...
C)
...


Chapter 13: What If C==C?
The 3? It’s ignored; there’s no place to store it
...
After all, Enter
ends standard input
...

Run the GREATER program again — this time, entering $ and pressing the Enter
key at the first prompt
...

See the Enter key displayed? It’s what separates the ‘ at the end of the third
line and the ‘ at the beginning of the fourth line
...
After all,
Enter is a key on the keyboard and a proper character code, just like anything
else
...
That leaves
you with the EOF character
...

In Unix, type $ and then pressCtrl+D
...
Obviously,
explaining something like that to the users who run your programs would
be bothersome
...
Keep reading
...
That’s ASCII code 27
...
That’s ASCII code 4
...
In Unix, the Ctrl+D combo works instantly
...


Fixing GREATER
...
C is to ensure that all standard input is cleared
out — purged or flushed — before the second getchar() function reads it
...

The C language function fflush() is used to clear out information waiting to
be written to a file
...
Here’s the format:
fflush(stdin);

You can insert this statement into any program at any point where you want
to ensure that no leftover detritus can accidentally be read from the keyboard
...

To fix the GREATER
...
This code snippet shows
you how the fixed-up source code should look:
printf(“Type a single character:”);
a=getchar();
fflush(stdin);
printf(“Type another character:”);
b=getchar();

Add the new Line 10, as shown here, to your source code for GREATER
...
Save
the changes to disk
...
The program now properly
runs — and you can continue reading about comparing characters with the
if command
...
I have
noticed that it’s required for Unix, Linux, and Mac OS programs
...
What it
really does is read standard input, which for nearly all computers I have used
is text typed at the keyboard
...
Some versions of GCC
for Windows use the getch() and getche() functions, which can read text
directly from the keyboard and lack the standard input problems of getchar()
...

To read the keyboard directly in Unix, you have to access the terminal being
used and then interpret which keyboard codes are being generated
...

Alas, this book doesn’t have room to describe all these keyboard-reading func­
tions
...


Meanwhile, back to the GREATER problem

Now that you may have ironed out the problem with getchar() in the
GREATER program, it’s time to examine the output
...
Try to see whether the ‘–’ character is greater than
the ‘$’
...
Rather than compare the character’s physique, if compares the
character’s corresponding ASCII code values
...
The code value for the dollar sign
is 36
...
This also holds true for letters of the alphabet and their ASCII
code values
...
Instead, you compare
whatever keystroke was entered with a known, desired choice
...

ߜ See Appendix B for a gander at ASCII values
...
The big Z is less than the little A, even though A comes before Z in the
alphabet
...
The uppercase letters have
smaller values than the lowercase letters do, so “a-z” always is greater
than “A-Z”
...
Because I was curious, I thought I
would look it up
...

Our alphabet is based on ancient alphabets,
which in turn are based on even older, dinosaurage alphabets
...
B was named
after a house and shaped like a door
...
That’s how it was for most of
the early Semitic languages, which used phon­
ics rather than pictographs or ideographs
...
The Romans stole their alphabet from

the Greeks (the Romans stole just about every­
thing)
...
They left out a few sounds they didn’t
think they needed: (theta), U, V, X, Y, and Z
...
(The theta was never added by the
Romans, though some middle English scripts
used a Y symbol to represent it
...
”)
That sort of explains how the alphabet got to be
in alphabetical order
...
There’s probably a
story to tell there, but at this stage in the book,
I’m just too lazy to look it up
...
Here’s an example:
#include ...
Whew!\n”);
}
else
{
printf(“OK: Configuring computer to explode now
...
Save it to disk as BLOWUP1
...


Compile and run
...

What can the user type? Who cares! As the programmer you know that you
type a big N to make the computer not explode
...
Type N and press Enter:
Okay
...
(Even little N works
...

ߜ Well, the computer doesn’t explode, which you should have figured out
by now
...

ߜ Yes, this program has its limitations
...


Using the if Keyword to

Compare Two Strings

The if keyword cannot be used to compare strings
...

ߜ If you try to use if to compare two strings, the result is, as they say,
unpredictable
...

ߜ C All-in-One Desk Reference For Dummies (Wiley) has information about
comparing strings
...
That extra stuff involves good oldfashioned Mr
...

Unlike with math, most people don’t go running and screaming from logic
...
If they
did, no one would ever play the lottery or visit Las Vegas
...
But I digress
...
First is the logic of
properly laying out the decision that if makes: whether to use < or >= and
other silly things like that
...
It’s enough to drive you insane! This
chapter helps prevent that
...

Once upon a time, a study was done on the “usability” of a particular program
...
Normally, it’s the Enter key that users expect to press, but with
that one program, pressing the Enter key caused something odd to happen,
which required three or four steps to undo and returned users to the original
question
...
They blamed themselves rather than assume that the pro­
gram behaved in an illogical way
...
But, as the budding
programmer you’re becoming, even you know that such a thing is really easy
to change
...
C program, which I show
you how to create in Chapter 13
...
Yet the program was written so that only the N
key press — one key of many possible keys — prevents the computer from
blowing up
...

When giving the user a choice and one option is better than another, make it
very easy for them to accidentally select the best option
...
C program, the code should probably look like this:
printf(“Would you like your computer to explode?”);
c=getchar();
if(c==’Y’)
{
printf(“OK: Configuring computer to explode now
...
Whew!\n”);
}

The only option in this example that truly blows up the computer is pressing
the Y key
...

Of course, the best option is to limit input precisely
...

ߜ You may have noticed this illogic in Chapter 13, when you first ran the
BLOWUP1 program
...

ߜ Most Yes or No questions wait for either Y or N to be pressed and ignore
any other key (except for maybe Esc)
...
C program also presents an interesting problem
...
That’s easy! Instead, I mean what about the little Y key?
In the preceding section, when the program runs, the user can only press the
Y key to blow up the computer
...
C:
#include ...
\n”);
printf(“Bye!\n”);
}
else if(c==’y’)
{
printf(“OK: Configuring computer to explode now
...
Whew!\n”);
}
return(0);
}

Edit the original source code for BLOWUP1
...
Primarily, you’re checking for Y to begin with, and an else if
block is added to confirm checking for baby Y
...

Save the modified source code to disk as BLOWUP2
...


177

178

Part III: Giving Your Programs the Ability to Run Amok
Compile and run
...
” But, if you type a
Y or a y, the computer blows up (supposedly)
...


ߜ By making the program specifically check for the Y/y key press, you make
every other key on the keyboard a No selection
...
Logical, even
...
For example,
the following modification to Line 7 adds a common key-choice gizmo to
the question:
printf(“Would you like your computer to explode? (Y/N)”);

This line lets users know that they can press Y or N
...
For example, the BLOWUP2
...
\n”);
printf(“Bye!\n”);
}

Whenever you see repetition like that in a program, it generally means that you
have a better way to do things
...
A better option is
to use the OR logical operator so that the if command reads like this:
If variable a is equal to ‘Y’ or if variable a is equal to
‘y’

which becomes
if(a==’Y’ OR a==’y’)

Then, all you need to know is that, in C, the logical operator for OR is two pipe
characters: ||
...
” If either one is true, the set of statements belonging to the if
command is executed
...
h>
int main()
{
char c;
printf(“Would you like your computer to explode?”);
c=getchar();
if(c==’Y’ || c==’y’)
{
printf(“OK: Configuring computer to explode now
...
Whew!\n”);
}
return(0);
}

The major modification is with the if condition, which now compares two
operations with a logical OR
...

Save the changes to disk as BLOWUP3
...
Compile
...
Then run it:
It’s logically cured twice!
ߜ The pipe character is also known as the vertical bar
...

ߜ Sometimes the pipe character has a break in the middle, and sometimes
it’s a solid line
...

ߜ A condition must be on either side of the ||, logical OR, comparison
...
Each condition must be its own comparison, using
the operators in Table 12-1, over in Chapter 12
...

The || is the logical OR operator
...


Logical Operators Used in if Comparisons

Table 14-1
Operator

Meaning

“True” Examples

||

Or

true || true
true || false
false || true

&&

And

true || true

The logical operator is used on two standard if command comparisons
...
If both are true, the &&, logical AND condition is also
true and the entire statement passes; the printf() function then displays
the string
...


Table 14-2

Figuring Out a Logical AND Operation

Temperature

temperature>65

45

45>65
FALSE

72

72>65

(and)

temperature<75

Logical AND result

45<75
&&

TRUE
72<75

FALSE

Chapter 14: Iffy C Logic

Temperature

(and)

temperature<75

Logical AND result

TRUE
90

temperature>65

&&

TRUE

TRUE

90>65

90<75

TRUE

&&

FALSE

FALSE

According to Tables 14-1 and 14-2, both conditions that if evaluates must be
true for the logical AND to work
...
In that case, the AND test also fails
...
That’s fine; as long as they’re valid if command comparisons,
they’ll work
...


Table 14-3

Figuring Out a Logical OR Operation

Score, cheat_code

score>100

50,Z

50>100
FALSE

200,Z

200,Y

||

||

FALSE

FALSE

FALSE

TRUE

‘Y’==’Y’
||

200>100
TRUE

Logical OR result

‘Z’==’Y’

50>100
FALSE

cheat_code==’Y’
‘Z’==’Y’

200>100
TRUE

50,Y

(or)

TRUE

TRUE

‘Y’==’Y’
||

TRUE

TRUE

Table 14-3 shows how the logical OR judges comparisons
...
Unlike the logical AND, where
both (or all) conditions must be true, it takes only one comparison to make
the entire if statement true
...
You
can, however, compare more than one
...
All
the following examples are legal, though they may take some mental work to
figure out:
if(key==’A’ || key==’B’ || key==’C’)

In the preceding line, the if statement is true if the value of the character vari­
able key is either A, B, or C
...

In the following example, all three conditions must work out TRUE for the entire
statement to be true: The temperature value must be greater than 70 and the
value of sun must equal the value of shining and the value of weekend must
equal the constant YES
...

if(temperature>70 && sun==shining && weekend==YES)

The next one takes a little brain grease:
if(status==1 || user==ROOT && timer
Logical statements read from left to right
...

But then that is evaluated against timer being less than MAX, which must be
true for the entire statement to be true
...

ߜ You can easily remember that the && means “logical AND” because the
ampersand character is used to mean “and” in English
...

ߜ Multiple && and || conditions are evaluated from left to right (just like you
read)
...

ߜ There’s a difference between && and & (a single ampersand)
...
The same goes for || and |; use || in an if
statement
...

These may or may not be covered in this book’s companion, C All-in-One
Desk Reference For Dummies (Wiley)
...

The & character is simply a stylized combination of an e and a t
...

It’s another — the final — modification to the BLOWUP series of programs:
#include ...
Whew!\n”);
}
return(0);
}

Start editing with the source code from BLOWUP3
...
Save the final result to disk as BLOWUP4
...

Compile
...
Run
...
Both
must be typed at the keyboard to properly authorize the computer to blow
up
...

ߜ This program uses the fflush(stdin) command (in Line 9) to clear
input from the first getchar() function
...

ߜ If you’re using a Unix-like operating system, substitute fpurge(stdin)
for Line 9
...

ߜ The logical AND operator && ensures that both variables c and d must
equal the proper values for that part of the if statement to be true
...

Then, that result is compared with d==0, which must be true
...
Funky
...
Humans? We think that it’s punishment to tell a kid to write
“National Geographic films are not to be giggled at” 100 times on a chalkboard
...
They enjoy it, in fact
...
The only problem with that is getting them to
stop, which is why you need to know how if works before you progress into
the looping statements
...

ߜ To find out about the if statement, refer to Chapters 12 though 14
...


For Going Loopy

Doing things over and over is referred to as looping
...
The loop is
called such because it’s a chunk of programming instructions — code — that
is executed a given number of times
...


186

Part III: Giving Your Programs the Ability to Run Amok
As an example of a loop, consider the common Baby-Mother interaction
program:
Baby picks up spoon
...

Mommy picks up spoon from floor
...

Repeat
...
The loop is based on “Repeat,” which
tells you that the entire sequence of steps repeats itself
...
Therefore, it’s what is known as an endless loop
...
)
A simple modification to the program can fix the endless loop situation:
Repeat until Mommy learns not to put spoon before Baby
...

In conclusion, loops have three parts:
ߜ A start
ߜ The middle part (the part that is repeated)
ߜ An end
These three parts are what make up a loop
...
” The middle part consists of
the instructions that are repeated over and over
...

ߜ The C language has several different types of loops
...

ߜ The instructions held within a loop are executed a specific number of
times, or they can be executed until a certain condition is met
...
” Either way, several instructions are
executed over and over
...
But while the loop is, well, “looping,” the same part of the program
is run over and over
...
C, a program which proves that com­
puters don’t mind doing things over and over again
...

Not while you sit back, watch them sweat, and laugh while you snarf popcorn
and feast on carbonated beverages
...
The for keyword creates a small loop that
repeats a single printf() command five times:
#include ...

The new deal here is the for keyword, at Line 7
...
Notice that the line which begins with for doesn’t end with a semi­
colon
...
(It’s exactly like the if statement, in fact
...
C
...
C by using your compiler
...
A
semicolon may be missing in for’s parentheses
...
You see the following displayed:
Ouch!
Ouch!
Ouch!
Ouch!
Ouch!

Please,
Please,
Please,
Please,
Please,

stop!
stop!
stop!
stop!
stop!

187

188

Part III: Giving Your Programs the Ability to Run Amok
See? Repetition doesn’t hurt the PC
...

ߜ The for loop has a start, a middle, and an end
...
The rest of the loop,
the start and end, are nestled within the for keyword’s parentheses
...
)
ߜ Just as with the if structure, when only one statement belongs to the
for command, you could write it like this:
for(i=0 ; i<5 ; i=i+1)
printf(“Ouch! Please, stop!\n”);

The curly braces aren’t required when you have only one statement
that’s repeated
...

ߜ The for loop repeats the printf() statement five times
...
It’s called incre­
mentation, and you should read Chapter 11 if you don’t know what it is
...
Read
through this whole chapter, constantly muttering “I will understand this
stuff” over and over
...
But read
it all straight through first
...
For he’s a jolly good fellow
...
For why did you bring me here? An eye for an eye
...
Three for a dollar
...
For it can
be maddening
...
The for keyword defines a starting condition, an ending condition,
and the stuff that goes on while the loop is being executed over and over
...
Inside the parentheses are
three items, separated by two semicolons
...

The first item is starting, which sets up the starting condition for the loop
...
In OUCH
...

The second item is while_true
...
Typically,
while_true is a comparison, similar to one found in an if command
...
C, it’s i<5
...
In OUCH
...

The statement item is a statement that follows and belongs to the for key­
word
...
This statement must end with a semicolon
...
*/
}

Note that the statements are optional
...

ߜ One of the most confusing aspects of the for keyword is what happens to
the three items inside its parentheses
...

ߜ The biggest mistake with the for loop? Using commas rather than semi­
colons
...
Although that’s okay for them, I don’t recommend it for
beginners
...
Remember that
both semicolons are always required inside for’s parentheses
...
C a step at a time

I admit that the for loop isn’t the easiest of C’s looping instructions to under­
stand
...
It would be easier to say, for example:
for(6)
{
/* statements */
}

and then repeat the stuff between the curly braces six times
...

To help you better understand how for’s three parentheses’ pieces’ parts
make sense, I use the following for statement from OUCH
...

The first item tells the for loop where to begin
...
This plain old C language statement
stuffs a variable with a value:
i=0

The value 0 slides through the parentheses into the integer variable i
...

The second item is a condition — like you would find in an if statement —
that tells the for loop how long to keep going; to keep repeating itself over and
over as long as the condition that’s specified is true
...
It’s the same as the following if statement:
if (i<5)

If the value of variable i is less than 5, keep going
...
Without this
item, the loop would repeat forever: i is equal to 0, and the loop is repeated
as long as i<5 (the value of i is less than 5)
...
However, the last item tells
for to increment the value of the i variable each time it loops:
i=i+1

Chapter 15: C You Again
The compiler takes the value of the variable i and adds 1 to it each time the
for loop is run through once
...
)
Altogether, the for loop works out to repeat itself — and any statements that
belong to it — a total of five times
...


Table 15-1 How the Variable i Works Its Way through the for Loop
Value of i

Is i<5 true?

Statement

Do This

i=0

Yes, keep looping←

printf()
...
(2)

i=1+1

i=2

Yes, keep looping←

printf()
...
(4)

i=3+1

i=4

Yes, keep looping←

printf()
...
Then, the second item — the comparison — is tested
...

As the loop works, the third part of the for statement is calculated and the
value of i is incremented
...
When those statements are done, the comparison i<5
is made again and the loop either repeats or stops based on the results of that
comparison
...
However, it’s the best way in your C programs to repeat a group of
statements a given number of times
...
It’s true whether for has zero, one, or
several statements belonging to it
...
They
remember that the first item means “start here,” but they think that the
second item is “end here
...
” It works like an if comparison
...


191

192

Part III: Giving Your Programs the Ability to Run Amok
ߜ Don’t forget to declare the variable used in for’s parentheses
...
Refer to
Chapter 8 for more information about declaring variables
...
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
...
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
...
This program uses
a for loop to count to 100 and display each number on the screen
...
(Refer to your phone bill to see what I mean
...
C is similar to OUCH
...
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 ...
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
...
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
...


Chapter 15: C You Again
The printf statement displays the value of the integer variable i by using the
%d placeholder
...

Save the file to disk as 100
...
(It’s a chess-club joke; C in Roman numerals is
100
...
)
Compile the program and run it
...
It’s amazing how fast the computer can do that
...

ߜ Change the for statement in Line 5 of your 100
...
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
...
It doesn’t take the computer that much
longer to count to 10,000; but it does take longer to display all those
numbers
...
It’s only
by using loops that programs become useful
...
It’s all thanks to loops
...
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
...
C — which I proudly proclaim as
the first useful program in this book
...
C does is to display the ASCII
characters and their corresponding codes, from Code 32 on up to Code 127
...
(If
you program for any length of time, you look up ASCII codes almost hourly
...
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
...

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

Compile the program by using your compiler
...

ߜ I use this program all the time to quickly scope out ASCII code values
...
C program starts with the value 32
...

The incrementation is done by the handy a=a+1 equation in the for keyword’s parentheses
...
To avoid duplicate output,
however, both the %d and %c placeholders are used in printf()’s format
string
...
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)
...
C can be either an integer or a
character variable
...

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
...


Chapter 15: C You Again
ߜ Here’s another secret: The variable a must be declared as an unsigned
character
...
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
...
C source code and recompile, and then
the program runs forever, which probably isn’t what you want
...


Beware of infinite loops!

Some things are eternal
...
Diamonds, of course
...
And, some loops can be eternal, though you don’t really want them to be
...
Moody programmers prefer the term infinite,
as in “It goes on forever and never stops
...

The infinite loop is a repeating section of your program that is repeated with­
out end
...
In fact, the infinite loop
is usually an accident — a bug — that pops up in a well-meaning 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
...

The following program is FOREVER
...
Using a misguided for command, the program repeats the
printf() statement ad infinitum:
#include ...
It’s similar to the first for-loop pro­
gram in this chapter, OUCH
...
The difference is in the for loop’s “while true”
part and the message that is repeated
...
C
...
Even though the for statement contains a deliberate
infinite loop, no error message is displayed (unless you goofed up and typed
something else)
...
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
...
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
...

ߜ 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
...
C is doing (over and over)
...
If Ctrl+C doesn’t work, often you have to use your
operating system’s abilities to kill off the program run amok
...

ߜ 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
...
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
...

ߜ Some compilers may detect the “forever” condition in the for statement
and flag it as an infinite loop
...
For example, the old Bor­
land C++ compiler flagged FOREVER
...
The compiler still produces the finished (and flawed)
program, though
...
For most loops,
that escape clause is provided in the looping statement itself
...

Some loops, however, are designed without an end
...
In that case, the loop is designed
to be eternal — which is fine, as long as some condition elsewhere eventually
breaks the loop
...
The loop sits and scans the keyboard, over and over, waiting
for you to type a command
...
It’s like a controlled infi­
nite loop — it’s not really infinite because you have a way out
...
C, a first stab at a word processor, though
you can do nothing in the program except type and see what you type on the
screen
...
The break
keyword is then used with the if command to bust out of the loop when you
press the ~ (tilde) key:
#include ...
Be careful as you type it into your editor
...
C
...
C
...
You can
type away and fill the screen with text
...
(This is
TYPER’s only “command
...

ߜ The for(;;) statement doesn’t error
...

ߜ I read the for(;;) command aloud as “for ever
...
C is infinite because its “while true” condition is
missing
...

ߜ The first and last parts of the for statement’s items aren’t included either,
though the semicolons inside the parentheses are still required in order
to meet the demands of C etiquette
...

ߜ The getchar function waits for a key to be pressed on the keyboard and
displays that character
...

ߜ The if statement tests the ch variable to see whether it’s equal to the
~ (tilde) character
...
If the comparison
is true, indicating that the user pressed the ~ key, the break command is
executed
...


The break keyword

The break keyword gets you out of a loop — any loop in C, not just a for loop
...
The program continues with the next
statement after the loop:
break;

Chapter 15: C You Again
The break keyword is a C language statement unto itself and must end prop­
erly with a semicolon
...

break can stop any loop, at any time
...
Based on the results of the test, the loop is stopped by
using break (just as was done with TYPER1
...

ߜ break stops only the loop it’s in
...
See Chapter 18 for more information on nested loops
...

ߜ It’s funny how the word is break and not brake
...


199

200

Part III: Giving Your Programs the Ability to Run Amok

Chapter 16


C the Loop, C the Loop++
In This Chapter
ᮣ Incrementing variables with ++
ᮣ Decrementing variables with -ᮣ Using other math operator shortcuts

L

ooping is a core part of programming, just as compromising your princi­
ples is central to getting ahead in politics
...

Just as loops flip through various iterations, variables are incremented or
decremented to help the computer keep track of things
...

The time has come for your full exposure to that ancient art and mysterious
practice of incrementation
...
For example:
for(i=0;i<7;i=i+1)

This for statement sets up a loop that is repeated seven times, from i=0 and
up by 1 seven times as long as the value of i is less than 7 (i<7)
...
The C lords prefer to start loops
with the counting variable at 0 because that’s where the computer itself starts
counting internally
...

Keep in mind that the for statement is merely a frame for a loop
...
The for statement itself only
controls the looping
...

So, no matter what the original value of the variable count, it’s 1 greater after
this equation:
count=count+1;

Face it: This equation is an awkward thing to look at
...

Even so, few C programmers use the preceding statement
...
The difference here is
that ++ works without an equal sign
...
Thank you
...
” It’s quick and
tidy, but a bit cryptic (which is why I didn’t throw it at you right away)
...

ߜ Yes, that’s why C++ is called “See plus plus
...

ߜ You don’t need an equal sign when you use ++
...

ߜ The equation i++ is the same as i=i+1
...

ߜ This area is where the C language begins to get truly cryptic
...
” But toss i++ at them and they
think “i plus plus? Weird
...
C program

Chapter 11 touches on the idea of incrementing a variable in a program
...
C, which I’m certain is near and dear to your heart and has
impressed many a friend and family member
...
Seriously, all those gauche w=w+1 things need to be properly changed
to w++ commands
...
Sweet
...
It’s what computers are all about!
The following program is an update to the LARDO
...
Load that old file into
your editor and make the necessary changes so that the program looks like
the source code listed here:
#include ...
h>
int main()
{
char weight[4];
int w;
printf(“Enter your weight:”);
gets(weight);
w=atoi(weight);
printf(“Here is what you weigh now: %i\n”,w);
w++;
printf(“Your weight after the potatoes: %i\n”,w);
w++;
printf(“Here you are after the mutton: %i\n”,w);
w=w+8;
printf(“And your weight after dessert: %i pounds!\n”,w);
printf(“Lardo!\n”);
return(0);
}

203

204

Part III: Giving Your Programs the Ability to Run Amok
Edit your source code
...

Save the file to disk again, using the same name, because this program is so
much more superior to the original
...

Fix any errors if you got ’em
...
The only true difference? You took advantage of the incrementation
operator, ++, and earned the clever wink of sophisticated C language pro­
grammers worldwide
...
The reason is that the vari­
able w is increased by 8, not just by 1
...


The Mysterious Practice
of Decrementation
Loops don’t necessarily have to go forward
...

Consider OLLYOLLY
...
And, that’s about all
it’s good for:
#include ...

The only strange stuff you encounter is in the for loop’s parentheses, which
may look a little funky — but it’s counting backward! Will the loop work? Will
the computer explode? Is Jane really cheating on Ralph? How can this be
happening?

Chapter 16: C the Loop, C the Loop++
Quit pondering and type
...
C
...
Run it
...
And, it did it in a for loop with
what looks like a minimum of fuss — but still a little techy
...

ߜ To prove that you’re not going crazy, refer to Chapter 15’s 100
...

It counted from 1 to 100 using a for loop
...

ߜ Backward-counting loops in C are rare
...


O, to count backward

Counting backward or forward makes no difference to the computer
...

To count forward, you increment a variable’s value
...


205

206

Part III: Giving Your Programs the Ability to Run Amok
To count backward, you subtract 1 from a variable’s value, which is exactly
the way you do it in your head: 10, 9, 8, 7, and so on
...
If b came in with a value of
5, this statement sets b’s value to 4
...

ߜ Decrementing, or subtracting 1 (or any number) from a variable’s value
is just common subtraction
...

ߜ Incrementing means adding (1) to a variable’s value
...

ߜ Decrementing works because C first figures out what’s on the right side
of the equal sign:
b=b-1;

First comes b-1, so the computer subtracts 1 from the value of variable b
...

The variable is decremented
...
C program:
for(count=10;count>0;count=count-1)

It’s basic for loop stuff
...
The parts are listed in Table 16-1
...
The
loop begins by setting the value of the count variable equal to 10
...
But,
each time the loop repeats, the value of the count variable is decremented
...

Again, you have no reason to loop backward — except that the printf() state­
ment belonging to the loop displays the numbers 10 through 1 in a countdown
manner
...
It’s not only easier to do in your head, but it’s also less likely to be a
source for programming boo-boos than when you try to loop backward
...
The backward-counting loop in C is possible
but rarely used, mostly because counting is counting and it’s just easier
(for humans) to do it forward
...

ߜ Other than decrementing the loop’s variable, the only difference is in the
loop’s while-true condition (the one in the middle)
...
It’s
another reason that this type of loop is rare
...
The question arises: “Why bother?” Because you have to know about
decrementing and the cryptic -- operator, covered in the next section
...
(If you read the first half of this
chapter, you saw this coming from a mile back, most likely
...

Consider this example:
d=d-1

207

208

Part III: Giving Your Programs the Ability to Run Amok
This statement subtracts 1 from the value of variable d, decrementing it
...

Just like the incrementation operator, ++, the decrementing operator, --, works
like other mathematical operators in the C language
...
The -- tells the compiler to
subtract 1 from the associated variable’s value and — poof! — it’s done
...
I haven’t heard anyone say “minus-minus” — at least
not aloud
...

ߜ You suffer no penalty for using d=d-1 if you forget about the -- thing
...
Glue it to the end of the variable you want to decrement and
you’re done
...


A final improvement to OLLYOLLY
...
C program, by spiffing it up with the decrementation
operator
...
C into your editor again (if it’s not there right now) and
clickety-clack the down-arrow key to Line 7, where the for loop starts
...
Here’s how that line should look when you’re
done editing:

Chapter 16: C the Loop, C the Loop++
for(count=10;count>0;count--)

Save the source code file back to disk and then recompile it
...


More Incrementation Madness

Incrementation and looping go hand in hand like (this week’s) Hollywood’s
hottest couple
...
(Make that famous stage actor
...

Tied in with looping are the ++ and -- operators, which you can also use
independently from looping to increase or decrease a variable’s value — like
some actresses increase their bust size through various surgical techniques,
and their age via bald-faced lying
...
For example, the LARDO
...
The following statement
decreases w by 3:
w=w-3;

This is still a form of incrementing and decrementing, though values larger than
1 are used
...
And — as a bonus — you can use these types of
incrementing or decrementing in loops
...

ߜ Although you can increment a variable by a value larger than 1, the ++
operator increases a variable’s value by only 1
...

ߜ Fortunately, the C language lacks a +++ or --- operator
...
It’s a nice, polite, all-American
athletic chant that means either “You sad sacks were easy to beat and, if we
were unsupervised, we would be vandalizing your bicycles by now” or “You
defeated us through treachery and deceit and, if we were unsupervised, we
would be pummeling your heads with our aluminum bats
...
It’s a for loop that, yes, skips a bit as it counts
...
h>
int main()
{
int i;
for(i=2;i<10;i=i+2)
printf(“%d “,i);
printf(“who do we appreciate? GNU!\n”);
return(0);
}

Choose New in your editor and type the preceding source code
...
It goes
“double quote, percent sign, little d, space, double quote
...
C
...
Here’s what your output should look like:
2 4 6 8 who do we appreciate? GNU!

ߜ The loop starts at 2 and increments up to 10 by using the i=i+2 formula
...

ߜ You can change Line 7 of the program to have the loop count by even
numbers to any value
...
It
doesn’t do much for the chant, but it works
...
)

Chapter 16: C the Loop, C the Loop++

Counting to 1,000 by fives

The following program is an update to the old 100
...

In this case, the program counts to 1,000 by fives — a task that would literally
take days without a computer:
#include ...
Type the preceding source code
...
Indeed, it’s just a take-off from the old 100
...
Save
the file to disk as 1000
...

Compile 1000
...
Your screen fills with values from 5 to 1000,
all lined up in rows and columns
...
The i=i+5 operation keeps increasing the value of the i vari­
able by 5
...
It
stops counting at 1,000 because of the i<=1000 part of the loop
...


Cryptic C operator symbols, Volume III:
The madness continues
C is full of shortcuts, and mathematical operations are where you find most of
them clustered like bees over a stray Zagnut bar
...
But there are more!
To add 5 to a variable’s value, for example, such as in the 1000
...
” Unfortunately, it just
doesn’t look like that’s what it means
...
Sad news: It’s not
...
Table 16-2 lists the lot of them
...
The first one
uses the variable var, which is modified by a constant value, 5
...

Yes, the shortcuts for incrementing, decrementing, or changing a variable are
cryptic
...
You suffer no penalty for forgetting about
them
...

On your own: Modify the preceding two programs, CHANT
...
C
...

Answers are provided at the end of this chapter
...

Don’t memorize that term
...

ߜ Hey: It’s a good idea to stick a sticky note on Table 16-2 or flag it by dog­
earing the page
...

ߜ One way to remember that the operator (+, –, *, or /) comes first is to
look at the wrong way for subtraction:
var=-5

This is not a shortcut for var=var-5
...
Ipso fasto, var-=5 must be the proper way to
do it
...
Each of them can be a C language
statement unto itself, a mathematical operation to somehow pervert a
variable’s value
...



The answers
In CHANT
...
C, modify Line 7 to read:
for(i=2;i<10;i+=5)

In both cases, you change the longer equation i=i+x to its shorter variation,
i+=x
...

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
...

This chapter introduces you to the happy-go-lucky while loop
...
But, I have good news! while loops are a heck
of a lot simpler to understand
...


The Lowdown on while Loops
While loops shouldn’t be strange to you
...

This simple example shows a while loop in real life
...
Your foot is
stepping on the brake as long as the light is red — a loop
...


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
...

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
...
This is the
essence of a while loop in C
...
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 bad because, well, I get into that in the
next section
...
C, a bril­
liant C program shown right next:
#include ...
C program,
from Chapter 15
...
Save the file to disk as HEY
...

Compile
...

Here’s what the output looks like:
Ouch!
Ouch!
Ouch!
Ouch!
Ouch!

Please
Please
Please
Please
Please

stop!
stop!
stop!
stop!
stop!

Brilliant
...

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

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

ߜ In HEY
...
Then,
it’s incremented inside the loop
...

ߜ 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
...

ߜ While loops are easy targets for the infinite-loop boo-boo
...

ߜ For a while loop to quit, something must happen inside the loop that
changes the condition that while examines
...
C uses a for loop, and HEY
...
Neither one is better than the other
...


217

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
...
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 party’s over, and the program goes on, sadder but
content with the fact that it was repeating itself for a while (sic)
...
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
...
If the condition is TRUE, the
statements enclosed in curly braces are repeated
...

Inside the curly braces are statements repeated by the while loop
...
The do_this part
needs to modify the while_true condition somehow so that the loop eventually
stops or is broken out of
...
For example:
while(ch!=’~’)

This statement says “While the value of variable ch does not equal the
tilde character, repeat the following statements
...
Knowing which sym­
bols to pronounce and which are just decorations is important to understand­
ing C programming
...
The same symbols used there are used
with while, including ==, <, >, and !=
...

ߜ When you apply the language of the while loop’s format to HEY
...
It’s
just followed with a group of statements in curly braces
...
This
is rather common:
while((do_this)==TRUE)
;

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

As an example, here’s the basic for loop from the program 100
...


219

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
...
You could say that if your fingers are tired, you can use a for loop
...
It’s easier to
see the different parts
...

Another advantage of the while loop is that it looks more graceful
...
Speaking of which
...
Indefinitely
...
Of course, nestled within the loop is a break statement that halts it
short, such as when some condition is met
...
C program into your
editor
...
The bulk of the program is the following for loop:
for(;;)
{
ch=getchar();
if(ch==’~’)
{
break;
}
}

This example reads “Forever do the following statements
...
If
so (if TRUE), the loop stops with a break statement
...
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
...
And, that sole statement simply reads characters
from the keyboard and stores them in the ch variable
...
C
...

After you see the Press ~ then Enter to stop message, type away
...

Press the tilde key to stop
...

ߜ There’s no need for a break statement in this loop because while auto­
matically halts the loop when ch equals a tilde
...
It means to
keep looping as long as ch does not equal the tilde character
...

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


221

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


C from the inside out

Although C can be a strict language, it can also be flexible
...
You can use the value immediately inside another function
...
You can use that character immediately and not store
it in a variable
...
” It’s one of the more flex­
ible things you can do with C
...
C program is a useful one to illustrate the example of C code
being written from the inside out
...
Or, put another way, the
getchar() function generates the key press
...
To wit:
while(getchar()!=’~’)
;

The drawback is that the character generated by getchar() isn’t saved any­
where
...

Reedit the TYPER2
...
h>
int main()
{
puts(“Start typing
...

Save the changes to disk as TYPER3
...
Compile and run
...
But, the code is much
tighter (albeit a little less readable)
...
” By illustrating the
several steps, you make your code more readable
...
Then, after you’re certain that the code
works, think about recoding from the inside out
...
That helps later, in case you ever need
to debug your code
...

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
...
While dead_horse is TRUE, the loop repeats
...

ߜ 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)
...

ߜ Yuck
...
Yuck
...
No,
there’s more than one way to weave a loop, particularly a while loop
...


The Down-Low on Upside-Down
do-while Loops
A while loop may not repeat — no, not ever
...

Witness the cold, cruel while statement:
while(v==0)

226

Part III: Giving Your Programs the Ability to Run Amok
If v doesn’t equal 0, the statements clinging to the underside of the while loop
are skipped, just as though you had written this:
if(v==0)

There’s an exception, of course — a kind of loop you can fashion that always
executes at least once
...
This type of loop is rare, but it has the charming aspect of always want­
ing to go through with it once
...

To add some drama, you supply the number it starts at:
/* An important program for NASA to properly launch
America’s spacecraft
...
h>
int main()
{
int start;
printf(“Please enter the number to start\n”);
printf(“the countdown (1 to 100):”);
scanf(“%d”,&start);
/* The countdown loop */
do
{
printf(“T-minus %d\n”,start);
start--;
}
while(start>0);
printf(“Zero!\nBlast off!\n”);
return(0);
}

Type this source code into your editor
...
C
...
Fix any errors
...
If you forget it, you get an error
...

Please enter the number to start
the countdown (1 to 100):

Be a traditionalist and type 10
...

T-minus 1
Zero!
Blast off!

ߜ The do while loop executes once, no matter what
...

ߜ Don’t forget the ampersand (&), required in front of the variable used in
a scanf statement
...


do-while details

A do-while loop has only one advantage over the traditional while loop: It
always works through once
...
” It’s guaranteed to repeat itself
...

The do keyword belongs to while when the traditional while loop stands
on its head
...
It’s as though the while
doesn’t even notice the condition until after the loop has wended its way
through one time
...
If the condition is true, the statements
in the loop are repeated
...
But, no matter what, the statements are always
gone through once
...
Mess it up and it’s sheer torture later to figure out what
went wrong
...
It has
no starting condition because the loop just dives right into it
...
In fact, it
may look like this:
starting;
do
{
statement(s);
do_this;
}
while(while_true);

Yikes! Better stick with the basic while loop and bother with this jobbie only
when something needs to be done once (or upside down)
...

You can use the same symbols used in an if comparison, and even use
the logical doodads (&& or ||) as you see fit
...
It has been said that only a mere 5 percent
of all loops in C are of the do-while variety
...
Only by using break, in
fact, can you halt the statements in the midst of the loop
...


A flaw in the COUNTDWN
...
When it asks you to type a number,
enter 200
...
But, 200 is out of the range the program asks you
to type
...
Hopefully, the DOS prompt or terminal window that
you’re using has this feature
...
You see something like this:
T-minus -5
Zero!
Blast off!

The do while loop is executed at least once, so the -5 is displayed
...

The way to guard against this faux pas is to write a special loop to ensure that
the value that is typed is kosher
...
That is han­
dled quite brilliantly by do-while
...
Okay: They’re
the range of numbers or letters or whatever that your program is looking for
...
C, they’re numbers from 1 to 100
...
Stuff like that
...
You have to make sure that they type only
40 or fewer characters
...
You must guard against this situation — and you can, if you
write your program correctly
...

It protects the program from this type of error in advance
...
If not, you can
either ask politely for input again or just print a rude error message
...
C program bulletproof, you have to have the pro­
gram ask for input again whenever the value that’s entered is either less than
1 or greater than 100
...
That way, you can ask the question the first time and it has to be
repeated only when the value that’s entered is out of range
...

You don’t have to change COUNTDWN
...
Just modify the first part
of the program to read:
do
{
printf(“Please enter the number to start\n”);
printf(“the countdown (1 to 100):”);
scanf(“%d”,&start);
}
while(start<1 || start>100);

The do-while loop asks the same question the program asked earlier
...
If either
condition is true, the loop repeats, asking the same question over and over
until a proper value is entered
...
C source code to disk
...

Run it:
Please enter the number to start
the countdown (1 to 100):

Type 0 and press Enter
...
Type 101 and press Enter
...
That’s
all made possible with a nifty do-while loop
...
Whenever you’re asked to type a value in a certain range or to
type fewer than so-many letters, a loop is in there, making sure that
you’re doing it right
...

ߜ Refer to Chapter 14 for more information about the logical || (OR)
comparison
...
But that’s another subject
...
It’s called
making a nested loop, or with one loop inside another
...
C program

What’s missing from the COUNTDWN
...
In case you
haven’t noticed, typing any value from 1 to 100 doesn’t really affect the speed
at which the countdown is displayed; after you press Enter, the text zips on up
the screen
...

The purpose of the delay loop is merely to spin the computer’s CPU, burning
up clock cycles to slow down the program at a certain point
...

Modify the second do while loop in the COUNTDWN
...
*/
#include ...
C resembles this source code,
which now has a nested loop, for purposes of delaying the text display and
output
...
Compile
...

If the output still runs too fast, change the value in the for loop from 100,000 to
1,000,000 (written like this: 1000000)
...

(If you need to go to 4,000,000, you need to declare the delay variable as an
unsigned long
...
Note
that both loops don’t need to be of the same type (two for loops or two
while loops)
...

ߜ The first loop, or outside loop, ticks off first
...
After that, the outside loop ticks off
another one, and then the inside loop is repeated entirely again
...

ߜ Keep separate the variables associated with one loop or another
...
This loop is infinite, in fact, because both are manipulating the
same variable in different directions
...
You write some huge pro­
gram and nest two for loops miles apart without thinking about it, by
using your favorite variable x (or i) in each one
...

ߜ The way to avoid messing up nested loops is to use different variables
with each one — for example, a or b, or i1 and i2, or even something
descriptive, such as start and delay, as used in the COUNTDWN
...

ߜ That nested for loop in COUNTDWN
...
Here’s another
way you could format it:
for(delay=0;delay<100000;delay++)
;

This example shows you that the for loop doesn’t have any statements
worth repeating
...

ߜ Although delay loops, such as the one shown in COUNTDWN
...
That is to use the computer’s internal
clock to time a delay of a specific duration
...

ߜ My first IBM PC — some 20 years ago — required a delay loop that
counted to only 10,000 for about a half-second pause between each line
displayed
...
Yes — I
said seconds
...

You can replace the for delay loop in COUNTDWN
...
But, it works
...
To delay
one second, for example, you use this command
in COUNTDWN
...


The nitty GRID
...
Most often, they happen when you’re filling
in a grid or an array
...
An example of how
it’s done is shown in the GRID
...
h>
int main()
{
int a;
char b;
printf(“Here is thy grid
...

Enter the source code into your editor
...
C
...
Notice that putting two for statements together doesn’t
cause the compiler to spew errors at you (unless you made a typo somewhere)
...
Here’s what the output should look like:
Here is
1-A 1-B
2-A 2-B
3-A 3-B
4-A 4-B
5-A 5-B
6-A 6-B
7-A 7-B
8-A 8-B
9-A 9-B

thy
1-C
2-C
3-C
4-C
5-C
6-C
7-C
8-C
9-C

grid
...
Such efficiency should please any government bureaucracy
...

ߜ The inner for loop may seem strange, but it’s not
...
The
character variable b starts out equal to the letter A and is incremented
one letter at a time, up to the letter K
...
The variable b then increments
up to the letter K’s ASCII value, which is 75
...

ߜ The printf() function displays the numbers and letters as the inner loop
spins
...
Then, the outer
loop is incremented, and the next row of letters is printed
...
That’s
what keeps the columns in the grid from running into each other
...
In
GRID
...


Break the Brave and Continue the Fool

Two C language keywords can be used to directly control loops in your pro­
grams
...
The break keyword should
be familiar to you, having been introduced in Chapter 15 and tossed at you
every now and again since then
...


235

236

Part III: Giving Your Programs the Ability to Run Amok
What continue does is to instantly repeat a loop
...
The fool!
ߜ Both break and continue are C language keywords and statements unto
themselves
...

ߜ Both break and continue work inside any C loop
...


Please continue
...
C, which isn’t named after the Muppet’s
Swedish Chef
...
h>
int main()
{
int x=0;
for(;;)
{
x++;
if(x<=5)
{
printf(“%d, “,x);
continue;
}
printf(“%d is greater than 5!\n”,x);
break;
}
return(0);
}

Type the source code for BORC
...
Save it to disk as BORC
...
(If you keep thinking of Bork-Bork-Bork,
you save it to disk as BORK
...
)
Compile and run the program
...
C program contains an endless for loop
...
After the value of x grows to be more
than 5, the continue is skipped and, finally, a break statement stops the end­
less loop
...
I read it as “for ever
...

ߜ The continue statement causes the rest of the loop — the printf() and
break — to be skipped, and then the loop is repeated
...

ߜ An else condition doesn’t have to be present to complement the if in
Line 10
...


The continue keyword

Like the break keyword, the continue keyword is used to affect how a loop
loops
...

The continue command comes in handy when you have statements in a loop
that you don’t want to repeat every time; continue just skips over them and
starts the loop over at the beginning
...

ߜ Like break, continue affects only the loop it’s in
...

The rest of the statements in the loop are just skipped, and the loop starts
all over
...
If you have a nested
loop, keep in mind that continue affects only one loop at a time
...


237

238

Part III: Giving Your Programs the Ability to Run Amok
ߜ Keep in mind that although continue forces another spin of the loop’s
wheel, it doesn’t reinitialize the loop
...

ߜ You should keep in mind only two real warnings about the continue
command: Don’t use it outside a loop or expect it to work on nested
loops; and be careful where you put it in a while loop, lest you skip over
the loop’s counter and accidentally create an endless loop
...
In fact, many C
programmers may be a little fuzzy on what it does or may not know pre­
cisely how to use it
...
But the word
loop works so much better than my alternative, structure thing
...
Well, anyway
...
It’s not so much a loop as it’s a wonderful method of
cleaning up a potential problem with multiple if statements
...
That’s what this chapter does
...
In fact, management at your local theater has just devised an

240

Part III: Giving Your Programs the Ability to Run Amok
interesting computer program to help cut down on pesky, hourly-wage employ­
ees
...
h>
int main()
{
char c;
printf(“Please make your treat selection:\n”);
printf(“1 - Beverage
...
\n”);
printf(“3 - Hot dog
...
\n”);
printf(“Your choice:”);
/* Figure out what they typed in
...
00\n”);
else if(c==’2’)
printf(“Candy\nThat will be $5
...
00\n”);
else if(c==’4’)
printf(“Popcorn\nThat will be $7
...
\n”);
printf(“I’ll assume you’re just not hungry
...
Save it to disk as LOBBY1
...
This should
brighten your heart because you know that more LOBBY programs are on the
way
...
Fix any errors
...

Watch your spelling and remember your semicolons
...


Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’
Run:
Please make your treat selection:
1 - Beverage
...

3 - Hot dog
...

Your choice:

Press 2, for Candy
...
50

Gadzooks! For Hot Tamales? I’m sneaking food in next time
...
Then, try an option not
on the list
...

I’ll assume you’re just not hungry
...


The switch-case Solution
to the LOBBY Program
Don’t all those else-if things in the LOBBY1
...
But it is rather clumsy
...
What you need is a
switch-case loop
...
Instead,
it’s a selection statement, which is the official designation of what an if state­
ment is
...
C program
...
C, an internal improvement to the
LOBBY1
...
It’s internal because you’re just messing with the program’s guts here — making them more elegant
...
h>
int main()
{
char c;
printf(“Please make your treat selection:\n”);
printf(“1 - Beverage
...
\n”);
printf(“3 - Hot dog
...
\n”);
printf(“Your choice:”);
/* Figure out what they typed in
...
00\n”);
break;
case ‘2’:
printf(“Candy\nThat will be $5
...
00\n”);
break;
case ‘4’:
printf(“Popcorn\nThat will be $7
...
\n”);
printf(“I’ll assume you’re just not hungry
...
C program in your editor
...
C
as a guide and edit what you see on your screen
...
Be careful
what you type
...
(The first few lines of the pro­
gram don’t change
...
Fix any errors or typos
...
The character constants are enclosed in
single quotes
...

Run
...
Internally, however, you
have converted an ugly string of if-else statements into an elegant decisionmaking structure: the switch-case loop (or “structure thing”)
...

ߜ The switch command in Line 19 takes the single character typed at the
keyboard (from Line 18) and tells the various case statements in its curly
braces to find a match
...
If there’s a match, the state­
ments belonging to that case are executed
...

ߜ If the break is missing, execution falls through to the next group of case
statements, which are then executed, no matter what
...

ߜ The final item in the switch-case thing is default
...


The Old switch-case Trick

This is one booger of a command to try to become comfy with
...
My advice is to work through the programs
in this chapter to get a feel for things and then check mark bullets in this
section for review purposes or to figure out what went wrong when things
don’t work
...
It should replace any long repetition of if-else
statements you’re using to make a series of comparisons
...
Here’s how it may look:
switch(choice)
{
case item1:
statement(s);
break;
case item2:
case item3:
statement(s);
break;
default:
statement(s);
}
choice must be a variable
...

After the case keyword come various items; item1, item2, item3, and so on
are the various items that choice can be
...
The case line ends in a colon, not in a
semicolon
...
The program exe­
cutes these statements when item matches the choice that switch is making —
like an if statement match
...

The statements are also optional
...
)
The last statement in a group of case statements is typically a break com­
mand
...

The last item in the switch structure is default
...
The default statements are executed no matter what (unless you
break out of the structure earlier)
...
For example, consider this program snippet:
switch(key)
{
case ‘A’:
printf(“The A key
...
\n”);
break;
case ‘C’:
case ‘D’:
printf(“The C or D keys
...
\n”);
}

Suppose that key is a single-character variable containing a character that
was just typed at the keyboard
...
The program
works:
switch(key)

Pick a key! So, key equals big A
...
The value of key equals the constant, big A
...
\n”);

Message printed
...
I’m done
...



Example 2: Suppose that a user presses the C key
...
It’s time to check the case statements for a match:
case ‘A’:

245

246

Part III: Giving Your Programs the Ability to Run Amok
Nope! Skip to the next case:
case ‘B’:

Nope! Skip to the next case:
case ‘C’:

Yup! There’s a match
...
What’s next?
case ‘D’:

The computer just goes ho-hum
...
Because the statements after
case ‘D’ are the first that it finds, it executes those:
printf(“The C or D keys
...
Then:
break;

The rest of the switch-case structure is skipped
...
Here’s how
the switch-case thing works:
switch(key)
key is an X
...
What’s left is the default, which supposedly
handles everything else — including the X:
default:

and the only statement:
printf(“I don’t know that key
...

ߜ The thing in switch’s parentheses (choice) must work out to either a
character value or an integer value
...
You can also put a C language statement or
function in the parentheses, as long as it works out to a character value
or an integer value when it’s done
...
The statements
belonging to case aren’t enclosed in curly braces
...
This statement tells the computer to skip over the rest of the
switch structure and keep running the program
...

That may not be what you want
...
If there’s a match, the statements belonging to
that case are executed; otherwise, they’re skipped
...
In that case, a match simply
“falls through” to the next case statement
...
For example:
case 56:

/* item 56 chosen */

or
case ‘L’:

/* L key pressed */

You cannot stick a variable there
...
You may want to
...
Give
up now
...
I use switch-case as a unit because it helps me remember that
the second word is case and not something else
...
If you leave it off and none
of the case’s items matches, nothing happens
...
But, within that while loop,
they usually have a nice, big switch-case structure
...
The over-and-over thing is a loop handled by while, and the
selection is done by a switch-case structure
...
C program:
/* Theater lobby snack bar program */
#include ...
\n”);

printf(“2 - Candy
...
\n”);

printf(“4 - Popcorn
...
\n”);

printf(“Your choices:\n”);

/* Figure out what they typed in
...
00\n”);
total+=8;
break;
case ‘2’:
printf(“Candy\t\t$5
...
5;
break;
case ‘3’:
printf(“Hot dog\t\t$10
...
50\n”);
total+=7
...
2f\n”,total);
printf(“Please pay the cashier
...
\n”);
}
/* end switch */
}
/* end while */
return(0);
}

Please type the source code for LOBBY3
...
You can try editing
the LOBBY2
...
Start from scratch, if you’re
willing
...
C
...
Fix any errors that may have crept into the code
...

2 - Candy
...

4 - Popcorn
...

Your choice:

To properly run the program, type your choices all at once and then press the
equal-sign (=) key and then Enter
...

For example, if you want a beverage and a hot dog, type 13= and then press
Enter
...
00
Hot dog
$10
...
00
Please pay the cashier
...
00
Candy
$5
...
00
Popcorn
$7
...
00
Candy
$5
...
00
Popcorn
$7
...
00
Candy
$5
...
00
Popcorn
$7
...

Improper selection
...

Candy
$5
...
50
Hot dog
$10
...
00
Total of $124
...


This is the last time I’m taking all you guys to the lobby!
ߜ Most programs employ this exact type of loop
...

ߜ One of the switch-case items handles the condition when the loop must
stop
...
C, the key is the equal sign
...
The while loop then stops repeating
...
So, by setting done equal to 0, by using
the ! (not), the while loop is executed
...

ߜ The various case structures then examine the keys that were pressed
...
At that point, the while loop continues to repeat as additional
selections are made
...
It’s a contraction of
total = total + value
...


our C language journey has been, I hope, a fun one
...
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
...

For example, why is it int main(), and what is the point
of the return(0); statement? I discuss what exactly
#include ...
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

F

unctions are where you “roll your own” in the C language
...
All that’s bundled into one package, which your program can then
use repeatedly and conveniently
...

If you’re familiar with computer programming languages, you should recognize
functions as similar to subroutines or procedures
...
It’s
a black box that does something wonderful or mysterious
...
This chapter definitely puts the fun into function
...
Yeah, I was getting sick of it too — C sick, in fact
...
Function

Are functions necessary? Absolutely! Every program must have at least one
function, the main() function
...
Beyond that, you don’t need
to create your own functions
...


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
...
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
...
A gaggle of play() functions
put together makes the computer whistle a tune
...
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’
...

ߜ You create a function by writing it in your source code
...
More on this later in this chapter
...
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
...
Calling (or using) a function is as easy as sticking its
name in your source code, just like any other C language statement
...
For exam­
ple, puts:
puts(“Oh, what a great way to start the day
...
That is, they produce something that your
program can use, examine, compare, or whatever
...

ߜ Other functions (such as playAlex()) neither require parentheses stuff
nor return a value
...
Most C programs are full of them, such as
printf(), getchar(), atoi(), and others
...
Even so,
the functions you write work just like those others do
...
How­
ever, you can use the function just like any other function in your pro­
grams; printf() and scanf(), for example
...
If any­
thing must be done more than once, shuffle it off into a function
...
It also breaks up the main() function in
your source code (which can get tediously long)
...
C, a litany of sorts devoted to some­
one named Bill, who is a jerk:
#include ...
Double-check all the parentheses and
double quotes
...
Maddening!

255

256

Part IV: C Level
Compile and run BIGJERK1
...
It displays the litany on the screen
...

Nothing big
...

Smells like a good opportunity for a function
...
Ah, but this is a demo
...
Feel free to change the name
Bill into someone else’s name, if you feel the urge
...
A message such as Bill is a jerk repeated over and over
meant that precious bytes of data were being wasted on a silly text string
...
Shaving a program’s size from
4,096 bytes to 3,788 bytes was considered a worthy accomplishment
...


The noble jerk() function

It’s time to add your first new word to the C language — the jerk() function
...
It’s a function
...
The compiler
doesn’t know the difference — as long as you set everything up properly
...
This pro­
gram is a major step in your programming skills — a moment to be savored
...
h>
int main()
{
printf(“He calls me on the phone with nothing say\n”);
printf(“Not once, or twice, but three times a day!\n”);
jerk();
printf(“He insulted my wife, my cat, my mother\n”);
printf(“He irritates and grates, like no other!\n”);
jerk();
printf(“He chuckles it off, his big belly a-heavin’\n”);
printf(“But he won’t be laughing when I get even!\n”);
jerk();
return(0);
}
/* This is the jerk() function */

Chapter 20: Writing That First Function
jerk()
{
printf(“Bill is a jerk\n”);
}

Type the source code for BIGJERK2
...
Pay special attention to
the formatting and such
...
C
...

The output from this program is the same as the first BIGJERK program
...
C: You may see a no prototype error; a Function should
return a value error; a ‘jerk’ undefined error; or even a no return
value error
...
Those are mere “warning”
errors — violations of C language protocol — not the more deadly, fatal
errors, which means that the program is unable to work properly
...

Hold fast
...
C
A function works like a magic box
...
In the case of the
jerk() function in BIGJERK2
...
Bill is a jerk — like that
...
C program, the computer ambles along, executing C language
instructions as normal, from top to bottom
...
The computer looks around and finds a jerk() function defined in your
source code
...
When it reaches the last curly brace in the function,
the computer figures that it must be done, so it returns to where it was in the
main program
...
C
...
Each time the com­
puter sees the jerk() function, it executes the commands in that function
...
C
program works
...


• printf("He chuckles it off, his big belly a-heavin'\n");
printf("But he won't be laughing when I get even!\n");

{


jerk();

printf("Bill is a jerk!\n");


}






ߜ The computer still reads instructions in the source code from the top
down in the main function
...
Then, it returns back to where it was
...
Most of
them contain many lines of code — stuff that would be too complex and
redundant to use all over the place in a program
...
It may seem like a silly thing to do, but it is in fact a good way to ensure
that functions are used properly — plus it helps you keep track of your code
...
But you probably
don’t trust it much either, so the respect is mutual
...

ߜ Typing comes from the Latin word for “what you do on a keyboard
...
First, you have to
properly configure the jerk function itself
...
C
source code to read:
void jerk()

This line tells the compiler that the jerk() function returns no values
...
(I cover
functions that return values in Chapter 22; functions that don’t return a value
are void
...
)
Second, you have to tell the compiler about the jerk() function way early in
the program
...
” You do this by sticking a line up top that looks like
the start of the jerk function — but ends with a semicolon:
void jerk(void);

Stick this line between the #include ...
The first part of your program looks like this:
#include ...
It tells the compiler to expect
a jerk() function later on in the source code
...
Furthermore, the
jerk() function doesn’t require any values, which is why a void is in its
parentheses
...
Just follow along if you don’t
understand it
...
A final rendition of
the BIGJERK2
...
h>
void jerk(void);
int main()

{

printf(“He calls me on the phone with nothing say\n”);


259

260

Part IV: C Level
printf(“Not once, or twice, but three times a day!\n”);
jerk();
printf(“He insulted my wife, my cat, my mother\n”);
printf(“He irritates and grates, like no other!\n”);
jerk();
printf(“He chuckles it off, his big belly a-heavin’\n”);
printf(“But he won’t be laughing when I get even!\n”);
jerk();
return(0);
}
/* This is the jerk() function */
void jerk()
{
printf(“Bill is a jerk\n”);
}

When you’re done, resave BIGJERK2
...
Recompile, and you shan’t be
bothered by the various warning errors again
...

ߜ The prototype must shout out what type of function the program is and
describe what kind of stuff should be between the parentheses
...
This is muy importanto
...
For example, in BIGJERK2
...

ߜ No, the main() function doesn’t have to be prototyped
...
(Well, almost
...
You may encounter older C source code files that
seem to lack any prototyping
...


A sneaky way to avoid

prototyping problems

Only the coolest of the C language gurus do this trick — so don’t tell anyone
that you found out about it in a For Dummies book! Shhhh!

Chapter 20: Writing That First Function
Face it: Prototyping is a mess
...
To wit, here’s another rendition of the BIGJERK program:
#include ...
C and make the changes in the preceding
program
...
Note that the jerk() function is defined as
void jerk(void), just like a prototype, but it’s the function itself
...
C
...
The
output is the same, but by turning the function upside down, you have utterly
removed the possibility of prototyping errors
...
Yes, the compiler is that smart
...
Rarely do programmers
know in advance which functions they need, so most programmers start
out coding functions the way it was done earlier in this chapter
...

ߜ Don’t add the semicolon to the function’s declaration when you list your
functions first! If you do, you get one of those nasty parse errors
...
If you have multiple
functions in your source code, order them so that if one function calls
another, that second function is listed first
...


The Tao of Functions

The C language allows you to put as many functions as you want in your source
code
...

ߜ What is “manageable size”? It depends
...

ߜ Often times, it pays to break off functions into their own, separate source
code files
...

ߜ This book’s companion volume, C All-in-One Desk Reference For Dummies
(Wiley), contains information on creating and managing multimodule
source code files
...
If the type
is void, the function doesn’t return any value
...
) Otherwise,
the type describes which type of value the function returns: char, int, float,
or any of the standard C language variable declarations
...
It must be a unique name, not any keywords
or names of other C language library functions, such as printf() or atio()
...
)
Parentheses after the function’s name are required, as they are on all C language
functions
...
I cover this subject in Chapter 22
...


Chapter 20: Writing That First Function
The statements belonging to the function require curly braces to hug them
close
...
Therefore, the full format for the function is shown here:
type name(stuff)
{
statement(s);
/* more statements */
}

The function must be prototyped before it can be used
...
For example:
type name(stuff);

This line, with a semicolon, is required in order to prototype the function
used later on in the program
...
(If you forget, your compiler may ever so gently
remind you with a barrage of error messages
...
Call it declaring a function
...
(The official term is defining a function
...

ߜ Your C language library reference lists functions by using the preceding
format
...
Its type is an int, and its stuff is a character string, which is how
you translate const char *s into English
...
h> thing is required at the beginning of
your source code when you use the atoi() function
...

Almost all compilers insist that your functions begin with a letter
...


263

264

Part IV: C Level
ߜ Don’t use spaces in your function names
...
For
example, this isn’t a function name:
get the time()

But this is:
get_the_time()

ߜ You can use upper- or lowercase when you’re naming your functions
...
For example, if the function is named
getTheTime and you type GetTheTime, you may get a linker error (the
function was not found)
...
A function named f()
is permissible yet ambiguous — it’s like saying “Nothing” when someone
asks you what you’re thinking
...
It sounds bizarre, I know, but the following may be verboten:
_whatever()

ߜ Avoid naming your functions the same as other C language functions or
keywords
...


Chapter 21


Contending with Variables

in Functions

In This Chapter
ᮣ Naming variables within functions
ᮣ Understanding local variables
ᮣ Sharing one variable throughout a program
ᮣ Using global variables

E

ach function you create can use its own, private set of variables
...

Just like the main() function, other functions require integer or character
variables that help the function do its job
...

This chapter introduces you to the strange concept of variables inside func­
tions
...
They’re unique
...


Bombs Away with the
BOMBER Program!
The dropBomb() function in the BOMBER
...
It could be an exciting ele­
ment of a computer game you may yearn to write, though you probably want
to use sophisticated graphics rather than the sloppy console screen used here:
#include ...
In the puts() function in Line 20 are 10
spaces before the asterisk
...

Save the file to disk as BOMBER
...
Compile and run
...

*
*
BOOM!
Yikes!

Yeah, it happens a little too fast to build up the nerve-tingling anticipation of
a true video game, but the point here is not dropping bombs; rather, the vari­
able x is used in the dropBomb() function
...
Nothing quirky
...
That’s how variables are used in functions
...
Refer to Chapter 8 for more information about declaring
variables
...

It has nothing to do with any values used inside the function
...
C
program bomb?
Modify the source code for BOMBER
...
Change the main() func­
tion so that it reads:
int main()
{
char x;
printf(“Press Enter to drop the bomb:”);
x=getchar();
dropBomb();
printf(“Key code %d used to drop bomb
...

This variable operates independently of the x variable in the dropBomb() func­
tion
...

The output is roughly the same for this modified version of the program; the
key code displayed for the Enter key “character” is either 10 or 13, depending
on your computer
...


ߜ Variables in different functions can share the same name
...
No biggie
...

ߜ Variable x not only is used in two different functions — independently of
each other — but also represents two different types of variable: a char­
acter and an integer
...


Adding some important tension

Face it: You’re going nowhere fast as a game programmer with BOMBER
...

What you need is some tension to heighten the excitement as the bomb

267

268

Part IV: C Level
drops
...
h>
#define COUNT 20000000

/* 20,000,000 */

void dropBomb(void);
void delay(void);

/* prototype */

int main()
{
char x;
printf(“Press Enter to drop the bomb:”);
x=getchar();
dropBomb();
printf(“Key code %d used to drop bomb
...
It’s the delay value
...
)

Chapter 21: Contending with Variables in Functions
Next, the delay() function must be prototyped:
void delay(void);

The delay() function is added into the dropBomb() function, right after
puts() displays the “bomb:”
delay();

Finally, the delay() function is written
...


Double-check your source code
...
Compile
...
This time, the

anticipation builds as the bomb slowly falls toward the ground and then —
BOOM!
ߜ The line used to create a constant (starting with #define) does not end
with a semicolon! Go to Chapter 8 if you don’t know about this
...
Note how much
easier it is than fishing through the program to find the exact delay loop
and value — one of the chief advantages of using a constant variable
...

ߜ What’s the point again? I think it’s that you don’t have to keep on think­
ing of new variable names in each of your functions
...
Just declare it and don’t worry about it
...

Most games, for example, store the score in a variable that’s accessible to a
number of functions: the function that displays the score on the screen; the
function that increases the score’s value; the function that decreases the value;
and functions that store the score on disk, for example
...
That’s done by creating a global variable
...
The main()
function can use it — any function
...
No problem
...
It’s what you have seen
used elsewhere in this book
...
C program
...

ߜ A global variable is available to all functions in your program
...

ߜ Global variables can be used in any function without having to redeclare
them
...
The variable has already been declared and is ready for
use in any function
...
After you declare x as a global variable, for example, no other func­
tion can declare x as anything else without ticking off the compiler
...
First, because they’re
global variables, any function in the program can use them
...
Out there
...
Midst the
chaos
...

For example:
#include ...

Think of this source code as the beginning of some massive program, the
details of which aren’t important right now
...
It’s done outside of any function, traditionally just before the
main() function and after the pound-sign dealies (and any prototyping non­
sense)
...

If more global variables are required, they’re created in the same spot, right
there before the main() function
...


Chapter 21: Contending with Variables in Functions
ߜ Global variables are declared outside of any function
...

ߜ Everything you know about creating a variable, other than being
declared outside a function, applies to creating global variables: You
must specify the type of variable (int, char, and float, for example),
the variable’s name, and the semicolon
...
C source code
...
That total is kept in the global variable deaths, defined
right up front
...
h>
#define COUNT 20000000

/* 20,000,000 */

void dropBomb(void);
void delay(void);

/* prototype */

int deaths;

/* global variable */

int main()

{

char x;

deaths=0;
for(;;)
{
printf(“Press ~ then Enter to quit\n”);
printf(“Press Enter to drop the bomb:”);
x=getchar();
fflush(stdin);
/* clear input buffer */
if(x==’~’)
{
break;

}


271

272

Part IV: C Level
dropBomb();
printf(“%d people killed!\n”,deaths);
}
return(0);
}
void dropBomb()
{
int x;
for(x=20;x>1;x--)
{
puts(“
*”);
delay();
}
puts(“
BOOM!”);
deaths+=1500;
}
void delay()
{
long int x;
for(x=0;x;
}

Bring up the source code for BOMBER
...
Make the necessary
changes so that your code matches what’s shown here
...
The loop allows you to drop bombs over and over;
pressing the ~ (tilde) key ends the loop
...
C to disk one more time
(though you don’t quite finish it until you read Chapter 22)
...


Chapter 21: Contending with Variables in Functions
The program effectively keeps a running tally of the dead by using the global
deaths variable
...
Both functions share that
global variable
...

ߜ No, this game doesn’t challenge you
...

ߜ The fflush() function is used to clear extra characters that getchar()
might read
...

ߜ In Unix-like operating systems, be sure to use fpurge(stdin) in Line 20
rather than fflush(stdin)
...


273

274

Part IV: C Level

Chapter 22


Functions That Actually Funct
In This Chapter
ᮣ Sending a value to a function
ᮣ Sending multiple values to a function
ᮣ Using the return keyword
ᮣ Understanding the main() function
ᮣ Writing tighter code

A

function is like a machine
...
I mean, functions must
chew on something and spit it out
...
Functions that funct
...
It’s done by sending a value to a function or by having a function
return a value
...


Marching a Value Off to a Function

Generally speaking, you can write four types of functions:
ߜ Functions that work all by themselves, not requiring any extra input:
These functions are described in previous chapters
...

ߜ Functions that take input and use it somehow: These functions are
passed values, as either constants or variables, which they chew on and
then do something useful based on the value received
...
For example, a function that computed your weight based on
your shoe size would swallow your shoe size and cough up your weight
...
Input and output
...
You call the whereEnt()
function, and it returns some galactic coordinates
...
It all depends on what you want the
function to do
...


How to send a value to a function

Sending a value to a function is as easy as heaving Grandma through a plate
glass window
...
Know what kind of value you’re going to send to the function
...
Either way, you must declare that value as the proper type so
that the function knows exactly what type of value it’s receiving: int,
char, or float, for example
...
Declare the value as a variable in the function’s parentheses
...
If so, you need to
declare that value as a variable that the function will use
...
Internally, the function refers
to the value by using the repeat variable
...
Somehow use the value in your function
...
(It’s a waste of memory
...
It’s a
warning error — and, heck, it may not even show up — but it’s a good
point to make: Use your variables!
4
...

You must do this or else you get a host of warning errors
...
Then, copy it
to up above the main() function
...


Chapter 22: Functions That Actually Funct
5
...

Because the function is required to eat values, you must send them along
...
Only by doing
that can the function properly do its thing
...
This term gives you a tiny
taste of C’s combative nature
...

ߜ You can treat the function’s parameter as a local variable
...
Yeah, it appears on the first line
...

ߜ By the way, the variable name used inside the function must match the
variable name defined inside the function’s parentheses
...

ߜ Information on passing strings to functions is provided in my book C Allin-One Desk Reference For Dummies (Wiley)
...
Although you can use global variables with a
function, the values the function produces or generates don’t have to be
global variables
...
)

An example (and it’s about time!)

Blindly type the following program, a modification of the BIGJERK
...
h>
void jerk(int repeat);
int main()
{

printf(“He calls me on the phone with nothing say\n”);

printf(“Not once, or twice, but three times a day!\n”);

jerk(1);

printf(“He insulted my wife, my cat, my mother\n”);

printf(“He irritates and grates, like no other!\n”);

jerk(2);

printf(“He chuckles it off, his big belly a-heavin’\n”);

printf(“But he won’t be laughing when I get even!\n”);

jerk(3);


277

278

Part IV: C Level
return(0);
}
/* The jerk() function repeats the refrain for the
value of the repeat variable */
void jerk(int repeat)
{
int i;
for(i=0;iprintf(“Bill is a jerk\n”);
}

You can edit this source code from the BIGJERK2
...
C
...
Don’t miss anything, or else you
get some nasty error messages
...

The program’s output now looks something like this:
He calls me on the phone with nothing say
Not once, or twice, but three times a day!
Bill is a jerk
He insulted my wife, my cat, my mother
He irritates and grates, like no other!
Bill is a jerk
Bill is a jerk
He chuckles it off, his big belly a-heavin’
But he won’t be laughing when I get even!
Bill is a jerk
Bill is a jerk
Bill is a jerk

The jerk() function has done been modified! It can now display the litany’s
refrain any old number of times
...
And look what it can do for your
poetry
...
The following check marks may clear up a few key issues
...

ߜ The new jerk() function repeats the phrase Bill is a jerk for what­
ever number you specify
...

ߜ The C-geek vernacular for sending a value of a variable to a function
is “passed
...
It can be
said, in a nerdly way, that the jerk() function has one parameter, an
integer variable (which is a number)
...
That’s one of the reasons that you prototype
functions
...

ߜ The variable repeat is not a global variable
...

ߜ Note that jerk() also retains its own variable, i
...


Avoiding variable confusion
(must reading)
You don’t have to call a function by using the same variable name the func­
tion uses
...
It’s a confusing concept,
but work with me here
...
You want to pass along its value to the jerk() function
...
Because count is an integer variable, this strategy
works just fine
...
The name count? It’s just a name in some function
...

In the jerk() function, the value is referred to by using the variable name
repeat
...

ߜ I bring this concept up because it’s confusing
...
Only inside that function is the function’s own
variable name used
...
You can find this subject in your C manual as well
...
However, you can call this function by using any
variable name or a constant value
...
What’s impor­
tant, however, is that it must be an integer variable
...
It can hold
more than one item — several, in fact
...
It’s like announcing them at some fancy
diplomatic function; each item has a type and a name and is followed by a
lovely comma dressed in red taffeta with an appropriate hat
...

For example:
void bloat(int calories, int weight, int fat)

This function is defined as requiring three integer values: calories, weight,
and fat
...
These values are referred to as repeat
and c inside the jerk() function
...
h>
void jerk(int repeat, char c);
int main()

Chapter 22: Functions That Actually Funct
{
printf(“He calls me on the phone with nothing say\n”);
printf(“Not once, or twice, but three times a day!\n”);
jerk(1,’?’);
printf(“He insulted my wife, my cat, my mother\n”);
printf(“He irritates and grates, like no other!\n”);
jerk(2,’?’);
printf(“He chuckles it off, his big belly aheavin’\n”);
printf(“But he won’t be laughing when I get even!\n”);
jerk(3,’!’);
return(0);
}
/* The jerk() function repeats the refrain for the
value of the repeat variable*/
void jerk(int repeat, char c)
{
int i;
for(i=0;iprintf(“Bill is a jerk%c\n”,c);
}

Type the preceding source code
...
C source
code as a base
...

Save the file to disk as BIGJERK5
...

Compile and run the program
...
To wit:
void jerk(int repeat, char c);
{
and so on
...


This declaration does the same thing, but it’s a
little more confusing because the variable name
is introduced first and then the “what it is dec­
laration” comes on the following line (or lines)
...

My advice is to stick with the format used in this
book and try not to be alarmed if you see the
other format used
...
Beware!

Functions That Return Stuff

For some functions to properly funct, they must return a value
...
This process is known as returning a
value, and a heck of a lot of functions do that
...

ߜ The function has to be defined as a certain type (int, char, or float, for
example — just like a variable)
...

ߜ The function has to return a value
...
For example:
int birthday(int date);

The function birthday() is defined on this line
...
(It also requires an integer parameter, date, which it
uses as input
...

Likewise, when a function doesn’t produce any output, it’s defined as a void:
void USGovernment(float tax_dollars)

The USGovernment() function requires very large numbers as input, but pro­
duces nothing
...
It’s easy to remember
...
Details appear later in this chapter
...

ߜ Another reason functions should be prototyped: The compiler doublechecks to confirm that the function is returning the proper value and that
other parts of the program use that int, float, or char value as defined
...
The float
variable, although it’s capable of handling a number in the trillions, is
accurate to only 7 digits
...
If the debt
were calculated as a float, it would lose accuracy around the $100,000
mark (like they care about values that small!)
...
It just doesn’t work that way
...

ߜ Functions can return only a single value
...
I know — it sounds like a gyp
...
Functions can return several values
...


283

284

Part IV: C Level

Finally, the computer tells you
how smart it thinks you are
The following program calculates your IQ
...
What’s more important
is that it uses a function that has real meaning
...
Well, ho-ho, the getval() function in the
IQ
...
h>
#include ...
\n”);
printf(“Enter your age:”);
age=getval();
printf(“Enter your weight:”);
weight=getval();
printf(“Enter the your area code:”);
area=getval();
iq=(age*weight)/area;
printf(“This computer estimates your IQ to be %f
...
C into your editor
...
(Does
that look familiar? I tell you more in a second!)
Save the source code file to disk as IQ
...


Compile
...


Here’s what the sample output may look like, using fictitious figures for myself:

Enter your age:33
Enter your weight:175
Enter your area code:208
The computer estimates your IQ to be 27
...


Of course
...
I’m not boasting or anything
...

ߜ By using this formula, only old, fat people living in low-numbered area
codes can get into Mensa
...
For example, the IQ value that’s calcu­
lated should be a floating-point number, and it’s not (unless your age,
weight, and area code are very special)
...
C by using the old type-casting trick
...
Inside getval(),
an integer value is produced by the atoi() function
...
Everything is an integer, so the function is of
that type as well
...
The values it pro­
duces (what it functs) is saved in the age, weight, and height integer
variables, respectively
...
Don’t! The
more tumid you are, the smarter the program makes you
...
Information just can’t fall off the edge, with the compiler assum­
ing that the last curly brace means “Hey, I must return the variable, uh, x
...
That’s it
...
Now I get it
...
C by using the old type-casting trick
In the IQ
...
All those variables are integers, and,
incidentally, it’s the exact formula used by my
kids’ school district
...
No, count on it
being a float
...

Decimals and fractions — it’s messy stuff
...
But
there’s a problem: The value calculated by the
equation is still stuffed into an integer
...
(Hey, the compiler
doesn’t assume anything, remember?)
To fix the problem, you must do something known
as type casting, where you tell the compiler to
temporarily forget what type of variable is there
and instead assume that it’s something else
...
C source code to read:
iq=(float)(age*weight)/area;

Insert the word float in parentheses right
after the equal sign
...

Compile and run
...
764423
...


No
...

The return keyword is used to send a value back from a function, to return a
value from the function
...
What kind of value?
It depends on the type of function
...
And, you can specify either a variable name or a con­
stant value
...

return(0);

The function returns a value of zero
...
For the void type of functions, you
can use the return(); statement by itself to cause the program to return,
for example, in the middle of something (see BONUS
...

ߜ Technically speaking, all functions can end with a single return; as their
last statement
...
(Execution falls off the
edge
...

ߜ void functions can use return, but it must not return anything! Just use
return(); or return; by itself in a void function
...

ߜ If your function is supposed to return something but has nothing to

return, use the return(0); statement
...
Sometimes, you have to use it in the middle of a function, such
as in BONUS
...


Now you can understand
the main() function
In all your programs, and in all the programs shown to this point in the book,
you have seen the main() function declared as an int and always ending the
return(0);
...

The value returned by main() is made available to the operating system
...
But, for some
programs, a return value is the way the program communicates with the
operating system
...
Any value other than 0 may indicate some error condition
...
The ERRORLEVEL variable in the batch
programming language stores the value
...


287

288

Part IV: C Level
ߜ Before the ANSI standard, the main() function was commonly declared
as a void:
void main()

You may see this line in some older programming books or source code
examples
...
(Nor has there ever been a documented
case of declaring void main() ever being a problem on any computer
...
If you don’t,
zillions of upset university sophomores will rise from the Internet to point
fingers at you
...


Give that human a bonus!

The following program, BONUS
...
This program proves that you can stick a
return plum-dab in the middle of a function and no one will snicker at you —
not even university sophomores:
#include ...
2f
...
33);
if(x==’1’) return(1
...
10);
}

/* Bottom-level bonus */
/* Second-level bonus */
/* Best bonus */

Chapter 22: Functions That Actually Funct
Type this source code into your editor
...
C
...
Also, the function is a float type,
which you haven’t yet seen in this book if you have been reading the chapters
in order
...

Here’s a sample of the output:
Enter employee name:Bill
Enter bonus level (0, 1, or 2):0
The bonus for Bill will be $33
...
Try not
to be impressed by its flexibility
...

ߜ You may have a temptation to type-cast the 100 in Line 15: b*=100;
...
If the 100 were
saved in an int variable — rate, for example — type casting would be
necessary:
b*=(float)rate;

ߜ Notice how the floating-point value 0
...
Values should
always begin with a number, not a decimal point
...
33 is spec­
ified, the compiler may choke
...

ߜ You may think of the statements in the bonus() function as being rather
brief
...

Actually, they are
...
In the following section,” you
can see several alternative formats that get the same job done
...


No Need to Bother with This C Language
Trivia If You’re in a Hurry
C is a flexible language that offers many ways to format a solution to a particu­
lar problem
...
C program
...


289

290

Part IV: C Level
The long, boring way:
float bonus(char x)
{
int v;
if(x==’0’)
{
v=0
...
50;
}
else
{
v=3
...
33;
else if(x==’1’)
v=1
...
10;
return(v);
}

And, without the integer variable v:
float bonus(char x)
{
if(x==’0’)
return(0
...
50);
else
return(3
...
33);
else if(x==’1’) return(1
...
10);
}

Finally, without the else:
float bonus(char x)
{
if(x==’0’) return(0
...
50);
return(3
...
C
source code
...


291

292

Part IV: C Level

Chapter 23


The Stuff That Comes First
In This Chapter
ᮣ Discovering how the #include thing works
ᮣ Creating your own header files
ᮣ Understanding how libraries work
ᮣ Using #define directives
ᮣ Ignoring macros

I

n case you haven’t noticed, there seems to be lots of detritus piling up
at the head of your C programs
...
There can be
#define things
...
Perhaps a
global variable is sitting up there in the yon
...
All that
stuff seems to pile up at the head of your source code, right before you get
into the meat of the matter with the main() function
...
Now that
you have most likely read all the other chapters and been roundly exposed
to the C language, a summary and description of those items is in order
...

ߜ An introduction to the #define thingy is in Chapter 8
...

ߜ Global variables are mulled over in Chapter 21
...
You use them when you write
several source code modules, which is an advanced topic, fully covered
in C All-in-One Desk Reference For Dummies (Wiley)
...
h>

It’s an instruction for the compiler to do something, to include a special file
on disk, one named STDIO
...

Figure 23-1 illustrates the concept for the #include ...

The contents of the STDIO
...

Figure 23-2 shows how several lines of #includes work
...


Say! Aren’t you the #include
construction?
The #include construction is used to tell the compiler to copy lines from a
header file into your source code
...
The header file contains
information about how the functions are used (yes, prototypes), as well as
other information that helps the compiler understand your program
...
The
filename must be in lowercase and typically (though it’s not a rule) ends
with a period and a little h
...
h>

The path is sys/, followed by the header filename, socket
...


Chapter 23: The Stuff That Comes First

STDIO
...
ΙΦ ψ
ου χαν, τηεν ψου∋ρε ϖερψ γοοδ
...
Αχτυαλλψ, ιφ ψ
ου∋ρε µψ εδιτορ, τηεν ψου∋λλ προβαβλψ
βε λοοκινγ φορ σοµε βαδ στυφφ
...
ΒΥΤ νοτ τηατ Ι∋µ
ωριτινγ τηισ στυφφ ιν ΓΡΕΕΚ, Ι δον∋τ τηι
νκ τηερε ωιλλ βε α προβλεµ ωιτη ιτ
...


Figure 23-1:
How an

#include ...


STDIO
...
ΙΦ ψ
ου χαν, τηεν ψου∋ρε ϖερψ γοοδ
...
Αχτυαλλψ, ιφ ψ
ου∋ρε µψ εδιτορ, τηεν ψου∋λλ προβαβλψ
βε λοοκινγ φορ σοµε βαδ στυφφ
...
ΒΥΤ νοτ τηατ Ι∋µ
ωριτινγ τηισ στυφφ ιν ΓΡΕΕΚ, Ι δον∋τ τηι
νκ τηερε ωιλλ βε α προβλεµ ωιτη ιτ
...


STDLIB
...
ΙΦ
ψου χαν, τηεν ψου∋ρε ϖερψ γοοδ
...
Αχτυαλλψ, ιφ
ψου∋ρε µψ εδιτορ, τηεν ψου∋λλ προβαβ
λψ βε λοοκινγ φορ σοµε βαδ στυφφ
...
ΒΥΤ νοτ τηατ
Ι∋µ ωριτινγ τηισ στυφφ ιν ΓΡΕΕΚ, Ι δον∋
τ τηινκ τηερε ωιλλ βε α προβλεµ ωιτη ιτ

...
h>
#include ...
h>
Figure 23-2:
Multiple
#include

thingies in a
program
...
H
Τηισ ισ σοµε ϖερψ σµαλλ τψπε τηατ ψ
ου προβαβλψ ωον∋τ βε αβλε το ρεαδ
...
ΙΦ
ψου χαν∋τ, ψου∋ρε τψπιχαλ
...

Ρεστ ασσυρεδ
...
Υνλεσσ, οφ χουρσε, ψου∋ρε ΓΡ
ΕΕΚ
...
The compiler looks for that
header file in the same directory as your source code file
...
Remember that the C language contains only some 32 keywords
(see Table 3-1, in Chapter 3)
...
Those functions are prototyped in the vari­
ous header files you include at the beginning of your programs
...

ߜ The
...

ߜ You know when to use a certain header file by looking up a function in
your C language library reference
...

ߜ Always use lowercase when you’re writing out an include directive
...

ߜ You need to specify a header file only once, even if two different func­
tions require it
...
For example, the compiler may report “435 lines compiled”
when your source code is only 20 or 30 lines long
...

ߜ A complete path to the header file isn’t necessary
...
Header files are located in a special
subdirectory installed on your hard disk with your C compiler
...
H files that came
with your compiler
...
(Please don’t change them!)
ߜ In Windows, the INCLUDE folder is found beneath the folder where your
compiler was installed
...


Chapter 23: The Stuff That Comes First

Long, tedious information that you want to miss
You may remember that I tell you how a text
file becomes a program
...
Anyway, I lied in
there
...
Before your compiler compiles,
it takes a quick look at your source code and
runs it through a gizmo called the preprocessor
...

Instead, it scopes out your source code for any
line beginning with a pound sign (#)
...

The compiler recognizes several preprocessor
directives
...
Others are used
for something called º which tell the compiler
whether to compile certain parts of your source
code — sort of like “If such-and-such is true,
ignore the following several lines
...


What’s up with STDIO
...
h> thing forces the compiler to look on disk
for a file named STDIO
...
No, you don’t see it done; it happens as your source code is converted
to object code
...
”)
The STDIO
...
(It’s not pronounced “studio-h,” though many people say
that
...
H defines all the prototypes for the standard I/O commands:
printf() and puts(), for example
...

You can view this file and its contents, as you can view any header file
...

In Windows, use this command:
type stdio
...
h

297

298

Part IV: C Level
Search through the file for some old friends, such as printf(), to see how
it’s defined and prototyped inside the header file
...
Not now, not ever
...

To get a feel for it, and because this chapter would be unduly short other­
wise, create the following header file, HEAD
...
Type the lines
exactly as written, matching lowercase for lowercase and uppercase for
uppercase:
/* This is my wee li’l header file */
#define
#define
#define
#define

HAPPY 0x01
BELCH printf
SPIT {
SPOT }

Save the file to disk as HEAD
...
You have to type the dot-H, lest your editor
save it to disk with a C, TXT, or DOC extension
...
Instead, you use it by #include-ing
it in your source code
...
Granted, it may
not look at all like a C program
...
Please, I beg, give me a few moments
before you run off all huffy to Mr
...
h>
#include “head
...
Type the preceding source code
exactly
...
h in double quotes
...
Also, don’t let
the SPIT, BELCH, SPOT stuff toss you
...


Chapter 23: The Stuff That Comes First
Save the file to disk and name it HTEST
...
Compile and run
...
Believe it or not, everything should work out just fine
...
HAPPY is happy
...
Here’s the blow-by-blow:
The second #include (Line 2) brings into your source code the HEAD
...
All the instructions in that file
are magically included with your source code when HTEST1
...
H)
...
H header file are a few of those #define direc­
tives, which tell the compiler to substitute certain characters or C language
words with happy euphemisms
...
H file, if you need to
...
So,
SPIT is used in the program rather than the first curly brace in Line 5:
SPIT

The word BELCH was defined to be equal to the word printf, so it serves as
a substitute for that function as well in Line 6, and in Line 8 you see the word
SPOT used rather than the final curly brace
...
#define statements are the most popular
...
Remember that because it’s eventually copied into
your source code, anything that normally would go there can also go into a
header file
...
A
doozy I wrote for one program, for example, listed all the #defines for
strange key combinations on the keyboard
...

ߜ Can’t remember the code for the happy face? Just #define it in your
own header file and use it instead, which is what is done here
...
However, the first #define in HEAD
...


299

300

Part IV: C Level

A final warning about header files

The typical header file used in C contains lots of information
...
By that, I mean that although the
printf() function may be defined, prototyped, massaged, and oriented
inside the STDIO
...

I mention this because occasionally a reader writes to me and says something
along the lines of “Dan! I need the DOS
...
Can you find it for me?” My answer is that even if I could
find it, the header file alone does not help
...

Library files are like object code: They contain instructions for the micro­
processor, telling it how to go about doing certain tasks
...

Figure 23-3 illustrates the process
...
C in the figure
...
H is #included, so it’s combined with the
source code by the compiler
...
O
(or HOLLOW
...

To turn the object file into a program file, a library is added
...
These are carefully linked
into your source code so that a final program, HOLLOW (or HOLLOW
...

It’s the library that contains the code, not the header file! If you want to com­
pile an older DOS program, you need an older DOS library to link into your
source code
...

ߜ Library files live in the LIB folder, which is usually found right next to
the INCLUDE folder
...

ߜ More information on using library files is in C All-in-One Desk Reference
For Dummies (Wiley)
...
C

Source code

STDIO
...
O

Object code

1010101010100
1101001111010
1001010010110

LIBC
...


Linker

HOLLOW
1010101010100
1101001111010
1001010010110

301

302

Part IV: C Level

What the #defines Are Up To

The #define directive is another one of those things the compiler eats
before it works on your source code
...

The full scope of the #define “construction” is offered in Chapter 8
...
Let me add, how­
ever, that #define is the most popular item placed into a header file
...
H file, in fact, and add these two lines:
#define TRUE 1
#define FALSE (!TRUE)

Save HEAD
...

What you have done is to create a shortcut word, TRUE, that you can use as a
“true” condition
...
The exclamation
point in C means not
...
(It works out
to be 0; no big deal
...
C:
#include ...
h”
int main()
SPIT
if(TRUE)
BLECH(“Must be true!\n”);
if(FALSE)
BLECH(“Never see this message
...
Save it to disk
...
Run
...
Refer to Chapters 17 and 18
...

ߜ Some C programmers prefer to define TRUE and FALSE this way:
#define FALSE 0
#define TRUE(!FALSE)

Whatever
...
If you see the preceding #defines in a program, every­
thing still works as advertised
...

ߜ Some compilers may issue a warning message when no comparison is
in the if statement’s parentheses
...

ߜ Some compilers may also point out that the second if statements are
never executed because the if condition is always false
...
Run
the program anyway
...
Like #include and
#define, macros are instructions to the compiler that tell it how to handle
conditions and whether specific parts of the source code are to be used or
skipped
...

Though there’s no reason to describe in detail what macros are and because
I’m not crazy enough to waste time with an example, you may see even more
pound-sign goobers playing the macro game in someone else’s C source code
...


303

304

Part IV: C Level
For example:
#if GRAPHICS
//do graphical wonders here
#else
//do boring text stuff here
#endif

Suppose that GRAPHICS is something defined earlier in the program or in a
header file — #define GRAPHICS 1, for example
...

Otherwise, the statements between #else and #endif are compiled
...

Crazy! Why bother?
I have used this trick only once: I wrote a program that had two versions —
one that ran on old color PC systems and a second that ran on monochrome
systems
...
Therefore, I used the
#if goober so that I needed to write only one source code file to create both
versions of the program
...
I’m mentioning it here
because it fits in the section heading and because some C poohbah
somewhere would chastise me for ignoring it
...
If it’s value isn’t 0, the #if con­
dition is true and the statements between #if and #endif are compiled
...

ߜ You may see some of the #ifdef or #ifndef things in various header
files
...

ߜ Another #-goober is #line
...
Supposedly, what it does is
force the compiler to report a unique line number just in case an error
occurs
...
)

Chapter 24


The printf() Chapter
In This Chapter
ᮣ Using printf() to display text
ᮣ Displaying forbidden characters with escape sequences
ᮣ Displaying the values of variables
ᮣ Understanding conversion characters

P

erhaps one of the most familiar fellows you have met on your C pro­
gramming journey is the printf() function
...
Now, after all that
time, this chapter is your formal introduction to the full power of printf()
...

ߜ printf() requires the backslash character — an escape sequence —
to display some special characters
...

ߜ The % conversion characters can also be used to format the output of
the information that’s printed
...
Here is its
most basic format:
printf(“text”);
text is the text you want to see on the screen
...


The double quotes are enclosed in parentheses, and the entire statement
must end with a semicolon
...
These
characters require the printf() escape sequences, as described in the
next section
...

ߜ To specify a double quote in your text string, use the \” escape
sequence
...
Most of these you
know from using them
...


Table 24-1

printf() Escape Sequences

Sequence

Shortcut for or Equivalent to

\a

Beeps the speaker

\b

Backspace (moves the cursor back, no erase)

\f

Form feed (ejects printer page; may clear the screen on
some computers)

\n

Newline, like pressing the Enter key

\r

Carriage return (moves the cursor to the beginning of the line)

Chapter 24: The printf() Chapter

Sequence

Shortcut for or Equivalent to

\t

Tab

\v

Vertical tab (moves the cursor down a line)

\\

The backslash character

\’

The apostrophe

\”

The double-quote character

\?

The question mark

\0

The “null” byte (that’s 0, not the letter O)

\Onn

A character value in octal (base 8)

\xnnn

A character value in hexadecimal (base 16)

The final two items in Table 24-1 are the most flexible
...

Suppose that you need to display the Escape character in your text
...
As an
escape sequence — an Escape escape sequence — that would be written as
\x1b

Here’s how it would look in printf():
printf(“On some consoles, this clears the screen \x1b[2J”);

You may want to flag this page with a sticky note or dog-ear the corner
...


The printf() escape-sequence
testing program deluxe
To see how some of these characters work, create the PRINTFUN
...
You modify the printf() statement at the core of the program to
demonstrate how the various escape sequences affect text:

307

308

Part IV: C Level
/*
printf() escape sequence demonstration program
*/
#include ...
Save it to disk as PRINTFUN
...

Compile and run PRINTFUN
...
Its purpose is to see how the \a sequence
“appears” in the text that’s displayed
...
How ghastly! Pray that you’re not testing this program in
the early afternoon, or else you may wake up your cellmates
...
This pause allows you to examine the output before the pro­
gram quits
...
The first
is \\, a double backslash that displays the backslash character
...
The
second escape sequence is at the end of the string, \a
...
The newline charac­
ter would goof up the display for some of the fancier escape sequences
(\r, \t, and \b)
...
This way, you can test all the sequences to
get a feel for what each of them does
...
Save the changes to the
program, compile it, and run it
...

That’s because \b backs up the cursor but does not erase
...
(If the cursor isn’t right there, you have a rogue space in the
program or you specified more or fewer instances of \b
...
C to look like this
and find out:
printf(“Here is the \\r sequence:\r”);

Save the change to disk, compile, and run
...
The carriage return resembles the carriage return on a typewriter: It
moves you to the beginning of the line
...

The \t character produces a tab, like pressing the Tab key
...
This is good for producing a
table in which text has to be lined up
...
The words Able, Baker, and Charlie
are separated by \t (tab) escape sequences
...
The same holds true for the two new lines: instances of \t separate the
numbers and words
...
Beware
of rogue backslashes, which you have a tendency to type as you enter each
line
...
C source code file to
disk
...
Run it
...
Tabular, dude!
ߜ The “tab stops” are preset to every eighth column in C’s output
...
I mention this because some
people assume that the tab always moves over eight (or however many)
characters
...

ߜ The \f and \v characters display special symbols at the Windows com­
mand prompt
...

Rather than a vertical tab, \v displays the male symbol
...
Just plug in
the hexadecimal code and there you go!

The Complex printf() Format

The printf() function can also be used to display the contents of variables,
which you have been seeing throughout this book with integer variables and
the %d placeholder, character variables and %c, and so on
...
]]);

Text still appears in double quotes, but after it’s used to display the values in
variables, it becomes a format string
...
)
The format string is followed by one or more variables, var
...
Those percent-sign place­
holders are called conversion characters
...
\n”,jerk);

The format string is text that printf() displays on the screen: Yeah, I
think ____ is a jerk, too
...
(I call them placeholders, but the lords
of C claim that they’re conversion characters
...
The jerk is a string vari­
able whose contents replace the %s in printf()’s output
...
Each conversion character, however, must have a cor­
responding variable; three %s characters would require three string
variables
...

ߜ You can specify both strings of text and numbers by using the proper
conversion characters, as described in the next section
...


The printf() Conversion Characters

Table 24-2 lists all the printf() conversion characters in the known
universe — even those you haven’t seen before and some you may never
see again
...
That
information is too complex and detailed to list
here for every compiler
...
However,
it comes in handy as you begin working with
numbers or require a little fancier output than
what you have done with printf() in this
chapter
...
The %p and %n are advanced conversion characters,
beyond the scope of this book
...

ߜ As with the escape sequences, the conversion characters are something
you use often but never remember
...

ߜ The %x, %e, and %g conversion characters also have uppercase equiva­
lents: %X, %E and %G
...
For exam­
ple, %x would display a hexadecimal value as 1ba2, but %X would display
1BA2
...

ߜ %p is used to print a value as a pointer
...


Chapter 25


Math Madness!
In This Chapter
ᮣ Using more complex math functions
ᮣ Understanding the pow() and sqrt() functions
ᮣ Linking in the math library for Unix
ᮣ Doing the post-/pre-increment/-decrement thing

M

ost people think that computer programming is all math
...
It involves math, to be sure, but the hard part — figuring out
the answer — is done by the computer
...
If you use a spread­
sheet, they’re the symbols you use to do math
...
The most cryptic one is the
asterisk (*), for multiplication
...

Therefore:
meals=breakfast+lunch+dinner;

314

Part IV: C Level
This equation, assuming that everything is a numeric variable, is correct
...
Always
...


ߜ You can always remember the cryptic mathematical symbols in the

C language by looking at your keyboard’s numeric keypad; each of the

symbols is right there
...
Some
operations, however, have priority over others
...

ߜ Another mathematical symbol is the %, which means modulus
...


ߜ It can be said that a C language operator exists for every odd symbol,
shape, jot, and tittle on your keyboard
...

Pray that you never have to memorize them all
...
Of course, I’m assuming
that you give a hoot about either of them, but you never know when they may
crop up
...
For example:
“Four squared” means 4 × 4, or 42
...

“Four cubed” means 4 × 4 × 4, or 43
...

Beyond cubed, or to the third power, you just say the power number; So,
4 × 4 × 4 × 4 × 4 is 45, or “four to the fifth power
...
There’s no cool
symbol
...
It would be nice, but it just isn’t so
...
A few dozen functions compute such things as power-of, square root,
terrifying trigonometric functions, and so on (see Table 25-1, later in this
chapter)
...

The pow() function is used to calculate one value taken to a certain power,
such as 4 taken to the second power (42)
...
The pow() function calculates n to the p
power
...

To prevent your compiler from going mad, you must include the MATH
...
Stick the following line up
there somewhere:
#include ...


Putting pow() into use

Using the pow() function is easy — it’s just like using any other function
...
H thing, and you’re all
set
...
Because he’s too smart to drive,
he directs you to go to the store and pick up 28 (“two to the eighth power”)
twinkly lights
...
h>
#include ...
f lights
...
Save the contraption
to disk as LIGHTS1
...

Compile and run
...


There
...
The computer suc­
cessfully concluded that 28 is equal to 256
...
In fact, many of
the MATH
...

ߜ Constant values, such as 2 and 8 inside LIGHTS1
...
Thankfully, the compiler is
pretty smart about that stuff
...
It works for both floats and doubles
...
part of %0
...

ߜ Some languages and spreadsheets use the caret symbol (^) for power, as
in 2^8 for 28
...
(The ^ in C is a bitwise
exclusive OR logical operation, whatever that means
...
The reason is that the standard C
library doesn’t come with those math functions
in it
...
The disad­
vantage is that you need to remember to link in
the math library when you write programs that
use math
...
c -o output

Follow gcc with the -lm switch
...
The input file is
source
...
To
properly compile lights1
...
c -o lights1

Again, this option is necessary only for pro­
grams that use high-level math functions
...


Rooting out the root

Another math problem you may have to work out is the square root
...
In any event, no keyboard symbol in C is used to calculate the
square root of a number
...

The sqrt() function is used to divine the square root of a number — to find
out which number, when multiplied by itself, equals the number you want the
square root of
...
In any event, it’s not the “squirt” function
...

Yes, everything must be double here
...
h>

317

318

Part IV: C Level
The only limitation on the sqrt() function is that n, the number you’re find­
ing the root of, cannot be negative
...

Because you and Milton have this light thing going, you’re going to surprise
him by telling him the square root of the number of lights you bought for
Christmas
...
C program
...
Be careful when you’re typing because
that long printf() line was split in order to fit into this book’s format; the
single backslash is used to show that the line continues on the following line:
#include ...
h>
#define TOOTH 253
int main()
{
double lights;
lights=sqrt(256);
/* square root of 256 */
printf(“Milton, I got your %0
...
\n”,\
lights,TOOTH);
return(0);
}

Save this puppy to disk as LIGHTS2
...
(Unix users, refer to the preceding sidebar, “Gotta link in
that math library!” for more details
...


The sqrt() function boasts that the square root of 256 is 16
...
Milton would be pleased
...
Is math great
or what?
ߜ Character code 253 is equal to the tiny 2 — the squared number
...
Even
if you can manage to get that symbol into your text editor, you still need
the sqrt() function to wrangle up a square root
...
Oh, well
...


Chapter 25: Math Madness!
ߜ No, sqrt() isn’t what the Roman legions paraded on their standards
...
)
ߜ A reader once wrote me e-mail asking whether the C language had some
equivalent of the mathematical i dingus, used to represent the imaginary
number √-1, or the square root of “negative one
...
Some mathematical C language
library somewhere may deal with i
...
(But I don’t do C++, so I can’t confirm it
...
Lots of them
...
Pretty much all of them want a double or float value, which makes
sense when you figure that if math had no decimals, more of us would enjoy it
...
H

standard

acos

Arc cosine

x=acos(y)

MATH
...
H

libm

atan

Arc tangent

x=atan(y)

MATH
...
H

libm

exp

Exponential

x=exp(y)

MATH
...
H

libm

log10

Base 10 logarithm

x=log10(y)

MATH
...
H

libm

tan

Tangent

x=tan(y)

MATH
...
Variables x, y,
and z are doubles
...
Refer to the earlier sidebar “Gotta link in that math
library!”

319

320

Part IV: C Level
ߜ The absolute value of a number is its value without the minus sign
...
Wise men truly run
from them
...
If you’re lucky, it’s in a book; otherwise, it’s in your compiler’s
online help feature
...
For example:
x=sqrt(1024);

Something Really Odd to End Your Day

It’s your old pal ++ again, and his sister, -- — the increment and decrement
operators from days gone by
...
For example, consider the following snippet of code that
you may find lurking in someone else’s program:
b=a++;

The variable b equals the contents of variable a plus 1
...
As such, doesn’t it work out
first? If so, does b equal a+1, or does b equal a and then a is incremented
after it all? And will Cody realize that Miranda is cheating on him so that he’ll
be free to marry Jessica? Hmmm
...


The perils of using a++

Here’s the rule about using ++ to increment a variable so that you know what
happens before running the sample program:
The variable is incremented last when ++ appears after it
...
Then, the value of a is incremented
...
C program
...
Save it to disk as INCODD
...
h>
int main()
{
int a,b;
a=10;
b=0;
printf(“A=%d and B=%d before incrementing
...
\n”,a,b);
return(0);
}

Compile and run! Here’s what the output looks like:
A=10 and B=0 before incrementing
...


The first line makes sense: The a and b variables were given those values right
up front
...
First, b is assigned the
value of a, which is 10; then a is incremented to 11
...

ߜ A good way to remember this rule is that the ++ comes after the variable
...

ߜ This rule screws you up if you ever combine the ++ with something else
inside an if comparison:
if(a=b++)

This technique is common — sticking the b++ inside the comparison
rather than on a line before or afterward
...

If the comparison is true, b is still incremented
...


321

322

Part IV: C Level

Oh, and the same thing applies to a -

The decrementing operator, --, also affects a variable’s value after any other
math or equal-sign stuff is done in the program
...
C program:
#include ...
\n”,a,b);
b=a--;
printf(“A=%d and B=%d after decrementing
...
C
...
Here’s the output, prov­
ing that decrementing happens after any math or assignments:
A=10 and B=0 before decrementing
...


The value of b is equal to 10, which means that the a variable was decre­
mented last
...
If you can’t remember the rule, just keep your
incrementing or decrementing on a line by itself, as shown in this example:
a++;
b=a;

Reflections on the strange ++a
phenomenon
Load the program INCODD
...
Change Line 10 to read
b=++a;

This line looks stranger than it is
...
It still increases the value of the a
variable
...
It reads “Increase me first, and then do whatever else comes
next
...
C to disk
...
Here’s what
you see:
A=10 and B=0 before incrementing
...


It worked! The ++a operation came first
...
Rarely have I
seen the ++ operator appear before a variable, but it can be done
...

ߜ You can use ++ before or after a variable when it appears on a line by
itself
...
++a is known as pre-incrementing
...
You can change Line 10
in DECODD
...
Variable a is decremented first, and
then its new value is given to variable b
...

ߜ Don’t even bother with this:
++a++;

Your logical mind may ponder that this statement first increments the a
variable and then increments it again
...
That message means
that the compiler was expecting another variable or number in there
somewhere
...


323

324

Part IV: C Level

Chapter 26


The Old Random-Number Function

In This Chapter
ᮣ Introducing the rand() function
ᮣ Seeding the rand() function
ᮣ Performing mod (%) calculations
ᮣ Producing random numbers in a given range

T

he original plans for this book had it run about 1,600 pages
...
The problem is that you cannot fit 1,600 pages into a roughly 400-page
book without cutting something out
...
I did that because, believe it or not, random
numbers are a big deal when it comes to programming a computer
...
No computer game would ever
be possible without a random number here or there
...


On Being Random

What’s random? The next card drawn from a well-shuffled deck
...
The spin of a roulette wheel
...
These are
all random, maybe-this-or-that events
...
After that’s done, no one can predict when the Enterprise will be
attacked or when the tornado will whip through your village or whether
Door Number 2 leads to the treasure this time or to certain peril
...

ߜ Random-number routines are the root of the most evil program ever
devised for a budding programmer: The Guess the Number program
...
(Well, maybe not
...
I formally introduce it next
...
I cover this subject also, later in this chapter
...
See the
nearby sidebar, “You too can waste a few seconds reading this informa­
tion about random numbers,” for more information
...
It spits
back a random number depending on the whims of your PC’s microprocessor
carefully combined with the birthdate of the guy who wrote your C compiler
plus his girlfriend’s weight in drams
...

Here’s the format for the rand() function:
int rand();

You too can waste a few seconds reading this
information about random numbers
Are they random numbers? Only if they can’t be
predicted
...
They’re still more or
less jumbled, like street numbers in Seattle
...
Instead, they’re
pseudorandom
...
But because

the number is based on a computer algorithm,
or set routine, its outcome isn’t truly random
...
So you live with it
...
If you want to save the random number into the r variable,
you use the following statement:
r=rand();

Cinchy stuff
...
h>

This line tells the compiler all about the rand() function and makes every­
one happy
...
RANDOM1
...
The
random numbers are produced by the rand function inside this program’s
rnd() function
...

#include ...
h>
int rnd(void);
int main()
{
int x;
puts(“Behold! 100 Random Numbers!”);
for(x=0;x<100;x++)
printf(“%d\t”,rnd());
return(0);
}
int rnd(void)
{
int r;
r=rand();
return(r);
}

Type the source code for RANDOM1
...
Double-check every­
thing
...
C
...
Fix any errors, which are probably limited to missing
semicolons or forgotten parentheses
...
I mean, would you have
thought of that many that quickly?
ߜ The random numbers are probably in the range of 0 to 32,000-

something — as promised
...


ߜ Some versions of the GCC compiler produce larger random number
values than 0 to 32,000-something
...
H header
...

ߜ To see the value of RAND_MAX on your computer, add this line to the pro­
gram before the return(0); in the main() function:
printf(“\nRAND_MAX is equal to %u\n”,RAND_MAX);
%u is the placeholder for an unsigned long integer
...
C
program again
...
Wait a second
...
The computer generated the set of random
numbers because that’s all it knows
...

Don’t feel cheated! This situation is a common one
...
To make it more random (more pseudorandom), you have
to plant a wee, tiny seed
...
To plant the seed, you use the srand()
function
...
Here’s the format:
void srand((unsigned)seed)

The seed value is an unsigned integer value or variable, ranging from 0 up to
65,000-something
...

You must include the following line at the beginning of your source code to
make the srand() function behave:
#include ...

ߜ The (unsigned) deal is used to ensure that the number srand() uses is
of the unsigned type (not negative)
...

ߜ Using the value 1 (one) to seed the random-number generator causes
the compiler to start over, by using the same, uninspirational numbers
you witness when srand() isn’t used
...


Randoming up the RANDOM program

Now comes the time for some really random numbers
...
C, a mild modification to the original program
...
h>
#include ...
You can start by editing the RANDOM1
...
Add the prototype for seedrnd() up front, and then insert the
call to seedrnd() in the main() function
...
Double-check the whole thing before
you save it to make sure that you don’t leave anything out
...
C
...
You see this line:
Enter a random number seed (2-65000):

Type a number, from 0 up to 65,000-something
...

The true test that it worked is to run the program again
...
The next batch of random numbers is completely
different from the first
...
Some purists insist on calling the seedrnd() func­
tion (or its equivalent) lots of times
...
No sense in wasting time
...
The statement
appears in Line 34:
seed=(unsigned)atoi(gets(s));

This line is a compilation of the following two statements:
gets(s);
seed=(unsigned)atoi(s);

First, gets() reads in a string variable
...

ߜ There’s no need for the seedrnd() function to return any values
...

This function is one of them
...


Streamlining the randomizer

Nothing annoys me like a klutzy program
...
When a program must
ask you to seed the randomizer, something is wrong
...
And it can, as long as it finds a source of everchanging numbers that it can use to seed the randomizer
...
Most PCs keep time down to the hun­
dredths of seconds: Every 1⁄ 100th of a second, a new number is available to
seed the randomizing gears
...
It just needs to be a number that’s different
from one second to the next, that’s all
...
C program
...
C except that the seedrnd() function now uses
the current time to seed the random-number generator:
#include ...
h>
#include ...
C in your editor
...
C
...
h>, which lets you
use the computer’s clock to seed the random-number generator
...
Save the file to disk
as RANDOM3
...

Compile and run the program
...
What you don’t notice is the program begging you to seed the ran­
domizer
...

ߜ The time() function in Line 31 returns the time of day from the computer’s internal clock
...
(This constant is defined in the
stdio
...
h> line sets it all up; see
Chapter 23 for more information
...
What’s important is that it’s an unsigned integer value,
which is what the (unsigned) type cast does
...
h>

ߜ And, this one:
#include ...
Modulus

You may have noticed that the random numbers produced by the RANDOM
series of programs have been wildly random and often unsuitable
...

You rolled a 23415 on the dice
...


You need to have a way to round down the numbers — a hacksaw to chop off

excess values and just give you numbers in a certain range, for example
...
It’s the mathematical concept modulus
...
” Well, 6 gazinta 10 is
modulo 4
...
The format is the
same for any of C’s mathematical operators
...

modulus = big % little;

Read it this way: If you take the huge number big and divide it by the smaller
number little, you get a remainder, which is the modulo value
...

The values of variable m for the following statement are either 0 or 1, depend­
ing on whether oddoreven is even or odd, respectively:
m = oddereven % 2;

For example, a die has six sides
...
To pare it to a multiple of 6, you use this line:
dice1=23415 % 6;

The computer calculates how many times 6 gazinta 23,415
...
(The result is the number 3, which is a more
realistic roll of a die than 23,415
...
Therefore, you want the larger value
to come first in a modulus operation
...
Pronounce it “mod
...

That’s all! You can dwell on the mathematical aspects of the % in other C
language books
...
” I point it out here because my managing
editor loathes it when I use nondictionary words
...

It produces a number in the range of 0 to 5 (0 to 5 as a remainder — you
can’t have a remainder of 6 when you divide by 6
...

ߜ In the My Dear Aunt Sally theme of things, a modulus operation comes
just after division and before addition
...

ߜ “Ah, yes, Dr
...
I’m familiar with your work in astrogenetics
...


Chapter 26: The Old Random-Number Function

Introducing My Dear Mother’s Aunt Sally (Ugh!)
Did you read about My Dear Aunt Sally in
Chapter 11? It’s a mnemonic device (a thing that
makes you remember something) for multipli­
cation, division, addition, and subtraction, which
is the order in which things get done in a long C
math statement
...
It goes like this:
My Dear Mother’s Aunt Sally:
*

Multiplication

/

Division

%

Modulus

+

Addition



Subtraction

Therefore, the following statement to get a roll
of the dice:
dice1=(23415 % 6)+1;

does the same thing without the parentheses:
dice1=23415 % 6+1;

The modulus operation (23415 % 6) comes
first regardless, and then 1 is added to the
result
...


Rolling the Dice with the Final
RANDOM Program
If you have been working through this chapter, you should have a whole pile
of random numbers spewing forth from your computer, like New Yorkers flee­
ing their buildings during an August power outage
...
It’s time to add an automatic range-finder
...
C (the last in the suite), has a rnd() func­
tion that coughs up random values only in the range of 0 to whatever number
you specify
...
h>
#include ...
h>
int rnd(int range);
void seedrnd(void);
int main()
{
int x;
seedrnd();
for(x=0;x<100;x++)
printf(“%i\t”,rnd(10));

335

336

Part IV: C Level
return(0);
}
int rnd(int range)
{
int r;
r=rand()%range;
return(r);
}
void seedrnd(void)
{
srand((unsigned)time(NULL));
}

Create the source code for RANDOM4
...
Start with your RANDOM3
...
Save the file
to disk by using the name RANDOM4
...

Compile and run the program
...

ߜ The rnd() and seedrnd() functions become handy as you write your
own C programs — specifically, games
...
Remember that both require
the #include directive, with seedrnd() also requiring
#include ...

ߜ To generate a roll of the dice, you stick the rnd() function in your pro­
gram and use this statement:
dice=rnd(6)+1;

/* Roll dem bones! */

ߜ Using the ever-collapsing C language function ability, you can rewrite the
rnd() function to only one statement:
return(rand()%range);

ߜ You’re now only moments from writing your own Monopoly game
...

for(item=1;item<11;item++)
{
printf(“This part of the book contains\n”);
printf(“various lists; ten items to a\n”);
printf(“chapter
...
\n”);
printf(“In the chapters that follow,
you’ll\n”);
printf(“find numerous lists, each with
ten\n”);
printf(“items that offer tips, tricks,
and\n”);
printf(“bonus information to help
conclude\n”);
printf(“your first voyage into the\n”);
printf(“C programming language
...
C has so much more ground to
be covered that it just couldn’t all possibly fit into this one book, at least
not at the same easygoing pace
...
(Note that these topics are all covered in this book’s compan­
ion volume, C All-in-One Desk Reference For Dummies, also published by Wiley
...
It allows you to store many different integers,
floating-point values, characters, strings, or any variable type in a single unit
...
But the three of them stored
together form an array
...
It can hold three
items, which is what the 3 in square brackets specifies
...
0, 98
...
6, 99
...

ߜ Each item inside the array can be referred to individually
...

ߜ The first element in an array is numbered zero
...
So element zero in the temps[] array is 97
...

ߜ Values are assigned to arrays just as they are to regular variables
...
(Note that the first element is zero
...
After you set, or dimension, an array to hold a specific number
of elements, that number is fixed and cannot be changed, which will
cause you endless frustration in the future
...


Strings
A string is nothing more than an array of characters
...
The contents of that
variable are Dan, or the letters D, a, and n
...
H as the word NULL or character code \0 (backslash zero)
...
Remember
that strings can contain characters, such as Enter and Tab
...

ߜ A string is nothing more than a character array
...

ߜ This book shows you how to use scanf() and gets() to read in strings
...

ߜ Many, many functions in the C language manipulate strings
...
Remember that you cannot use == in an if statement to com­
pare strings, but you can use the strcmp() or similar functions
...
It’s similar to a record in a database in that the structure variable
can be used to describe a number of different things all at once
...

Structures are declared by using the struct keyword
...
It contains two variables: an integer
named a and a character named b
...
To do that, you need
another line
...
The structure it
uses is of the type defined as sample:
struct sample s1;

Suppose that you’re writing a game and need some way to track the charac­
ters inside the game
...
It contains variables that describe
variable attributes of a character in the game: the character’s name, score,
strength, and location on the game grid
...
Here’s how
the name for character g1 are displayed:
printf(“Character 1 is %s\n”,g1
...
strength -= 10;

This statement subtracts 10 from the value of g2
...

ߜ Yes, structures are one way to do database work in the C language
...


Chapter 27: Ten More Things You Need to Know about the C Language

Pointers

Over in Chapter 1, I explain how the C programming language is a mid-level
language, containing both high-level and low-level programming attributes
...
Pointers are used in C to directly
manipulate the computer’s memory — specifically, variables stored inside
memory
...
I mean, why do you need a pointer
when you can change a variable’s value by using a function or an equal sign?
Yet, pointers give the C language a certain muscle power unlike any other
programming language
...

ߜ Pointers are declared by using the asterisk, which is confusing because
the asterisk also means multiplication
...

ߜ The number-one foul-up when it comes to pointers: not assigning them
before they’re used
...
I mean, duh!

Linked Lists

Want to terrify any university sophomore? Mention linked lists and they will
blanche with horror
...
But they’re really nothing devious — just a strange con­
cept because in order to know about linked lists, you must know about point­
ers
...

In the C language, linked lists combine the concept of an array with struc­
tures and pointers
...

But, unlike with an array of structures, you can add and remove structures
from the linked list easily
...

Binary operators work to manipulate the bits inside any C language variable
except for a float or double
...


Table 27-1

Bitwise Operators

Operator

Function

&

AND

^

Exclusive OR (EOR or XOR)

|

Inclusive OR

~

One’s complement

<<

Shift bits left

>>

Shift bits right

The only place I have seen these types of operators used are when programs
interact with the operating system or PC hardware
...

A special feature of the >> and << operators is that they perform superfast
binary division and multiplication
...
It’s much faster than using
this statement:
x = y/2;

To divide y by 4, you can use this function:
x = y >> 2;

Now, you have to think in binary to make this work, but it’s possible
...
But save that one for
another day
...
That’s one
way that a program can communicate with the operating system
...
For example:
grep pirntf *
...
The command has two command-line arguments: pirntf and *
...

These two strings of text are passed to the main() function as arguments as
well, which the program can then evaluate and act on, just as arguments
passed to any function
...
That too will have to wait for
another day
...
The C language is equipped with a wide variety of functions to read and
write information from and to the disk drives
...


Interacting with the Operating System

The C language also lets you perform operating system functions
...

You can also have your programs run other programs — sometimes two at
once! Or, your program can run operating system commands and examine
the results
...
You can even run services or prowl out on the
network
...


345

346

Part V: The Part of Tens

Building Big Programs

There’s nothing wrong with having a 50,000-line source code file
...
But I wouldn’t
recommend it
...
For example, one module may contain disk routines; another, initial­
ization; and another, routines to display things on the screen
...

That definitely saves time over the long haul
...
The
object files are then linked with various libraries to produce the final exe­
cutable file
...
In fact, you can share variables across differ­
ent source code modules, call functions in other modules, and do lots of
other cool stuff
...
There, you can find
an example of such a program, one that I hope will inspire you to go on to
bigger and better programming projects in the C language
...
Man, I wish I had had this list back in the steam-powered com­
puter days, when I first started learning how to program
...
Fortunately, most of the command-line shells out there
(in both Unix and Windows) have a command-repeat button
...
Pressing the up-arrow key again recalls the command before that
...


348

Part V: The Part of Tens

Keep Your Editor Open
in Another Window
The preceding tip can be null and void if you use your operating system’s
graphical environment
...
As long as
you can remember to save your source code, it’s perfectly fine to open a
separate window for your editor and use it to edit your source code file
...


Figure 28-1:
Switching

between

editor and

command-

prompt
windows
...
Or, use
the Alt+Tab key to switch windows, which seems to work in most graphical
environments
...


Use a Context-Colored Text Editor

This is why I recommend the Vim editor: As long as you put that
...
This feature is so
useful that if you ever go back to a monochrome editor, you notice that it
slows you down!
ߜ To activate the colors in Vim, type a colon, :, and then syntax enable,
and press Enter
...

ߜ In Unix, to keep syntax enable activated, edit or create a file named

...
Into that file, add or include the follow­
ing command:
:syntax enable

Then save the
...

ߜ Another bonus to highlighted text is that you can easily spot missing
quotes; text between quotes is color-coded, so if a quote is missing, the
source code looks like blech
...
Vim turns on
auto-indenting when you use the syntax-enable command, or choose
Syntax➪Automatic from the menu
...
If your text editor displays line numbers, you can
easily locate the specific line containing the error and then fix the error
...
To do so, first ensure that Word Wrap is off (choose
Format➪Word Wrap if necessary), and then choose View➪Status Bar
...
)
ߜ Vim displays the cursor’s position on the bottom of the window, toward
the right side
...
)
ߜ In Vim, the command to go to a specific line is G
...
Think “Line number, Goto” to remember this trick
...
It’s a window that contains the editor, plus other
gizmos for making Windows programs
...

One thing most IDEs don’t do is show you the output of the console pro­
grams created in this book
...
That way, you can type the names of the programs you create
and see their output in that window
...


Know a Few Handy Command-Prompt
Commands
I strongly advise that you become familiar with using a command prompt
...


Table 28-1

Command-Prompt Commands

Windows/DOS

Unix

What It Does

dir

ls

Lists all files in the current directory or folder
...


dir *
...
c

Lists only the C language source-code files in a
folder or directory
...


ren

mv

Renames a file; ren or mv is followed by the file’s
original name and then the new name, such as ren
goodbye
...
c or mv goodbye
...
c,
which renames the file goodbye
...
c
...

Use this command to ensure that you’re in the prog/
c/learn directory
...
c
cat source
...
c or rm bye
...


exit

exit

Closes the command-prompt window and closes the
terminal
...


Carefully Name Your Variables

Though I use a lot of single-letter variable names in this book, be a better,
wiser person when it comes to naming variables in your own programs
...

This may seem like a silly thing for a tiny program, but when your programs
get larger, you may find that that a quick x or a variable you declared is being
used by some other part of the program
...
But keep all your C language statements on a
single line, and remember that ++ or -- before the variable name does its job
before the variable’s value is used
...

Refer to Chapter 25 to find out about this concept
...
Whether that point is defined in the loop’s
controlling statement or set inside the loop by using a break command, be
sure that it’s there!
I recall many a time sitting at the computer and waiting for the program to
“wake up,” only to realize that it was stuck in a loop I had programmed with
no escape clause
...


Chapter 29


Ten Ways to Solve Your Own

Programming Problems

In This Chapter
ᮣ Work on one thing at a time
ᮣ Break up your code
ᮣ Simplify your job
ᮣ Talk through problems
ᮣ Set breakpoints
ᮣ Monitor variables
ᮣ Document
ᮣ Use debugging tools
ᮣ Use an optimizer
ᮣ Read more books!

W

elcome to the world of debugging
...
As it turns out, he was able to do it only
once — and it was a project he was well familiar with
...

Yes, your programs error
...
But your programs also have bugs
...
Well, all programs obey
their orders
...
It’s those times when you need to turn to this chapter and review
my ten ways of solving your own programming problems
...
The public will thank you!

354

Part V: The Part of Tens

Work on One Thing at a Time

Address your bugs one at a time
...

For example: You notice that the title is too far to the right, random characters
are at the bottom of the screen, and the scrolling technique doesn’t move the
top row
...
Instead, fix one problem
...
Then
fix the next problem
...
Catching those is easier if you remember that you
were working on, for example, only Lines 173 and 174 of your source code
...
I know that this topic isn’t covered in this book — and it probably
isn’t a problem you will encounter soon — but separate modules can really
make tracking bugs easy
...
Even consider announcing the
purpose of each section, such as
/*********************************************
Verification function
--------------------This function takes the filename passed to it
and confirms that it’s a valid filename and
that a file with that name doesn’t already
exist
...

*********************************************/

I also put a break between functions, just to keep them visually separated:
/********************************************/

Chapter 29: Ten Ways to Solve Your Own Programming Problems

Simplify

Avoid the temptation to gang up several commands on one line until you’re
certain that that part of your code works well
...
The more read­
able your code is, the easier it is for folks (including you) to find an error
...
Before then, you could have had
several potential trouble spots
...

Finally, when you’re certain that your code works, you can compact things on
one line — if you want to
...


Talk through the Program

One of the best ways to find bugs almost instantly is to show your code to
another programmer
...
What you do is start “talking through” the logic of your code
...

Suddenly, as you’re explaining what you did, you discover that one spot in
your code that doesn’t match your intentions
...

This technique of talking through your program works whether or not
another programmer is present
...
Does the bug lurk at the beginning of your code? In the initialization
routines? Just before the big math functions? Near the end? Where? Where?
Where?
One way to find out is to put breakpoints into your program
...
That way, you can narrow down the pesky code
...
If
the program doesn’t stop with the breakpoint, the fault lies before it
...
To confirm that the variables aren’t
carrying something outrageous, occasionally toss in a printf() statement to
display their values to the screen
...

For example, I had a program with a nasty endless loop in it
...
Talking through the source
code did nothing
...
I added a simple
if statement to fix the problem, and the program ran just fine afterward
...

Comment this! Comment that! I remember seeing classmates turn in projects
that were three pages of greenbar paper in length, and half of that consisted
of the dumb comments at the “top” of the program
...

True, document your work
...
It’s a reminder to say “This is what I was thinking”
or “Here is where my train of thought is going
...
This
comment is useless:

Chapter 29: Ten Ways to Solve Your Own Programming Problems
i++;

/* add one to the value of i */

Here’s a better comment:
/* Remember that zero is the first item, so increment
variable i here to account for that and not confuse
the user
...
In the future, it would
be cool to add a sound effect here, say, coins in a
hopper a la a slot machine
...
The
routine is supposed to work, but it keeps returning
a null value
...
*/

Use Debugging Tools

If your compiler features a debugger, use it! Debuggers let you surgically view
your program as it runs, monitoring variables and examining how the com­
puter literally steps through the code
...
This makes the
program huge and sluggish
...


Use a C Optimizer

Many fun tools out there examine your code and make suggestions for opti­
mization
...
Other tools exist as well; any C program­
ming Web site lists the variety — and many of them are open source (thank
you, open source community)
...
But they can help hone your code so that
it runs better
...
In fact, the whole Unix
operating system is designed around programming
...


Read More Books!

One question I often get from programming acolytes via e-mail is “What book
should I read next?” Well, obviously, the companion to this book, C All-in-One
Desk Reference For Dummies, (Wiley) is an excellent choice
...
You can find
books for programming networks, programming the operating system, pro­
gramming graphics, and on and on
...

ߜ As far as other programming languages are concerned, after reading
through this book, you will know about 95 percent of the C++ program­
ming language
...
But also
consider finding out how to use Perl, Java, Python, or any combination
of those languages
...

ߜ Above all, program
...
Devise new projects and work on ideas
...
Immerse
yourself in it
...

The purpose of this appendix is to outline what you need and how to use
it in order to work with the sample programs in this book
...
For Windows and
older Mac systems, you must obtain a compiler
...


360

C For Dummies, 2nd Edition

The C language compiler

Thanks to the C language’s popularity, many compilers are available for you
to use with this book
...
A list of compilers is provided on this book’s Web page, at www
...
com
...
It’s free and available from
www
...
net
...
You
have to use this location to create a batch file or modify your system’s path
so that you can access the compiler from any folder in your disk system
...

ߜ Other compilers are out there, including the best-selling Microsoft Visual
C++ (MSVC)
...
Note, however, that I’m not familiar with the
current version of MSVC and don’t refer to it in this book, nor can I
answer questions about it via e-mail
...

ߜ Plenty of free, shareware, and open-source C compilers are available on
the Internet
...

ߜ Any GCC- or GNU-compatible C compiler works best with this book
...
To
confirm, open a terminal window and type the following line at the command
prompt:
gcc -v

The version number of GCC and other information is displayed on the screen
...
(You can generally do that through your operating
system’s setup or configuration program; it doesn’t typically require that the
entire operating system be reinstalled
...
In
fact, you may notice that cc even works on other Unix-like operating systems,
where the cc command is often linked to the GCC compiler, for compatibility’s sake
...
I recommend the Code Warrior compiler, though you should also check
the Apple Web site to see whether any other (free) compilers are available:
http://developer
...
com/
...
These files include the
original-text source code files, the final program files, and perhaps even object
code files, depending on the compiler
...

For this book, I recommend creating a prog folder or directory
...
The prog folder is designed to hold all your programming
projects
...

Finally, create a learn folder, in which you put all the projects for this book
...

Windows
...
Open the My Documents icon on the desktop
...
Choose File➪New➪Folder to create a new folder and then name the
folder prog
...
Open the prog folder
...
Choose File➪New➪Folder to create a new folder, and then name it c
...
Open the c folder
...
Create a folder inside the c folder, and name that folder learn
...
Close the c folder window
...

Linux, FreeBSD, Mac OS X, or Unix: To create a folder for your C program­
ming projects, obey these steps:
1
...
You need to
get at the command prompt
...
If
you aren’t in your home directory, type the cd command to return there
...

2
...

With one command, you have created the prog directory, the c subdirec­
tory, and, finally, the learn subdirectory
...

You use the learn folder for storing all the source code and program files
created in this book
...
Alas, the old Mac operating system lacked a “home folder”
for all your stuff
...
Otherwise, you can create these folders right on
the desktop for handy access:
1
...

2
...

3
...

4
...

5
...

6
...

7
...

8
...

9
...

When using your compiler, remember to save all your files in the learn folder
...
You use the
editor to create or edit the source code — which is merely a text file
...

This book illustrates programming techniques by using small programs tar­
geted to showcase specific examples of the C language
...
I recommend that you become
familiar with the command prompt
...

If you’re using an older Mac, refer to your compiler’s documentation to find out
how to edit and compile programs
...


Finding your learn directory or folder

The first step to programming is to navigate your way to the learn directory
(or folder) by using the command prompt
...
Start a terminal or command-prompt window
...
EXE program, also known as the MS-DOS
prompt
...
Or, you can type CMD in the Run dialog box to start the
command-prompt window
...
Otherwise, any termi­
nal works
...
Change to your home directory
...
”)
In Linux, FreeBSD, or Mac OS X, type the cd command to change to your
home directory
...

3
...

Everyone, type:
cd prog/c/learn

except for older versions of Windows, where it’s
cd prog\c\learn

(Note the backslashes, not forward slashes
...
Confirm that you’re in the proper directory
...

The current directory is displayed, which should look like one of these:
C:\Documents and Settings\name\My Documents\prog\c\learn
C:\My Documents\prog\c\learn
/home/user/prog/c/learn
/Users/user/prog/c/learn

Note that the common part is the last part, prog/c/learn
...

The learn directory is where you’re working while you use this book
...


Running an editor

To concoct your C language source code, you need to use a text editor
...
It’s
rather simple to understand and use, it works with the mouse, and it’s free
and available
...
The
simplest text editor is Easy Editor, activated with the ee command
...


Appendix A: The Stuff You Need to Know before You Read All the Other Stuff
My favorite editor for working with C is vim, a variant on the infamous vi editor
in Unix (see Figure A-1)
...
When you edit
your source code in vim, you see keywords, values, and other parts of the C
language highlighted in color
...


ߜ Versions of vim are available for Linux, FreeBSD, Mac OS X, Windows, and
even older Macs
...
vim
...

ߜ Windows XP may not like the EDIT command
...
For example, to edit the GOODBYE
...
C

Notepad opens in another window, where you can edit the text file
...


Compiling and linking

After the source-code text file is created, your next step is to compile and
link
...

Read the proper subsection for compiling and linking specifics for your oper­
ating system
...


Making GCC work in Windows
Heck, for all the advances made with Windows, you may as well be using DOS
when it comes to compiling programs at the command prompt
...


365

366

C For Dummies, 2nd Edition
Windows compilers aren’t designed to be friendly for command-line compil­
ing
...
One way to make
that happen is to create a batch file that runs the GCC (or whatever) command
that runs the compiler
...

These steps assume that you have installed the Dev-C++ environment on your
PC
...

(If you installed Dev-C++ in another folder, you need to make a note of that
folder’s path
...
You must remember the path!)
Take a deep breath
...
Start a command prompt or MS-DOS window
...
See your favorite book on Windows for detailed
instructions
...
Change to the Windows folder:
cd \windows

(I’m assuming that Windows is the name of your Windows folder
...
)
Inside the Windows folder, you create a batch file program — a shortcut
to the GCC command used by Dev-C++
...

3
...
bat and press the Enter key
...
Carefully type this line:
@c:\Dev-C++\bin\gcc %1 %2 %3 %4 %5 %6

The line starts with an at sign, @
...
(If you have
installed GCC into another folder, put its path there instead; remember
to enclose the path in double quotes if it contains spaces!)
After gcc comes a space, and then %1, a space, %2, space, and so on
...

If all this seems strange to you, get someone else who better under­
stands Windows (or DOS) to help you
...
Review the line
...
Only when it looks like the example in this
book do you do the next step
...
Press the Enter key
...
Press the F6 key
...

8
...

You see 1 file(s) copied and the GCC
...

Now you need to test the GCC
...
Follow the
steps listed earlier in this appendix so that you’re in the learn folder
...

When you’re in the learn folder, type this command at the prompt:
gcc -v

If you see a whole lotta blech appear on the screen, congratulations! You got
it to work!
If it doesn’t work, review the preceding steps
...

Repeat the steps, and press Y after Step 3 to overwrite the current GCC
...


Windows: Compiling, linking, and running
After setting up the GCC
...

Eventually, you repeat the following steps often enough that you no longer
need to refer to this appendix for help
...
Ensure that you’re in the proper folder
...

2
...

Refer to Chapter 1 for the listing of the GOODBYE
...
Type that
text into your editor per the instructions in Chapter 1
...
Compile and link the source code
...
Here’s
the command to type:
gcc goodbye
...
c, the name of the source code file

• -o, the output switch

• goodbye, the name of the final program
If you leave off the -o switch and its option, GCC creates the program
file named A
...
I don’t recommend it
...
The name can
be the same as the source code file
...
C and program files end in
...
)
4
...

Type the program file’s name at the prompt
...
This step executes that program’s code and displays
something on the screen or does something interesting, depending on
what the program is supposed to do
...
As I have said, eventually it become second nature
to you
...
I cannot help you with problems
related to the compiler or its installation
...
That’s generally how things go in this book
...
The extra stage involves the creation of a
third file on disk — the OBJ, or object file
...

ߜ I recommend keeping the programs around for future reference; don’t
delete them until you have been programming a while and really no
longer need them
...
You eventually repeat these steps often
enough that you don’t have to return to see what’s next:

Appendix A: The Stuff You Need to Know before You Read All the Other Stuff
1
...

Heed the steps in the section “Finding your learn directory or folder,”
earlier in this appendix
...
Use your text editor to create your source code file
...
For an example, you can refer to the listing of the
GOODBYE
...

3
...

Compiling and linking are both handled by the GCC command
...
C
source code created in Step 1:
gcc goodbye
...
c, the name of the source code file

• -o, the output switch

• goodbye, the name of the final program
If you leave off the -o switch and its option, GCC creates the program
file named a
...
I don’t recommend this
...
The name can be the
same as the source code file, but without the
...

4
...

Alas, your operating system doesn’t run your program if you type its
name at the prompt
...
(If you create your own programs that you want to run, copy them
to a bin directory beneath your home directory, and put that directory
on the path
...

You do that by prefixing
...
To run the goodbye
program, type the following at the prompt:

...

Those steps are the basic ones you take (all in the learn folder) to create the
program examples in this book
...


369

370

C For Dummies, 2nd Edition
ߜ Filename extensions are optional in Unix, but I do recommend that you
use
...
That helps you keep
them straight
...
c and treat the file accordingly
...
That’s generally how things go in
this book
...
Usually, it’s -rwxr-xr-x, or the
equivalent of a chmod 755 command
...


Appendix B


ASCII Table
Code

Character

Hex

Binary

Notes

0

^@

00

0000 0000

Null character, \0

1

^A

01

0000 0001

2

^B

02

0000 0010

3

^C

03

0000 0011

4

^D

04

0000 0100

5

^E

05

0000 0101

6

^F

06

0000 0110

7

^G

07

0000 0111

Bell, \a

8

^H

08

0000 1000

Backspace, \b

9

^I

09

0000 1001

Tab, \t

10

^J

0A

0000 1010

Vertical tab, \v

11

^K

0B

0000 1011

12

^L

0C

0000 1100

Form feed, \f

13

^M

0D

0000 1101

Enter key, \n (or \r)

14

^N

0E

0000 1110

15

^O

0F

0000 1111

16

^P

10

0001 0000

17

^Q

11

0001 0001

18

^R

12

0001 0010

19

^S

13

0001 0011

Exit key (Unix)

(continued)

372

C For Dummies, 2nd Edition

Code

Character

Hex

Binary

20

^T

14

0001 0100

21

^U

15

0001 0101

22

^V

16

0001 0110

23

^W

17

0001 0111

24

^X

18

0001 1000

25

^Y

19

0001 1001

26

^Z

1A

0001 1010

End of file (DOS)

27

^[

1B

0001 1011

Escape

28

^\

1C

0001 1100

29

^]

1D

0001 1101

30

^^

1E

0001 1110

31

^_

1F

0001 1111

20

0010 0000

32
33

!

21

0010 0001

34



22

0010 0010

35

#

23

0010 0011

36

$

24

0010 0100

37

%

25

0010 0101

38

&

26

0010 0110

39



27

0010 0111

40

(

28

0010 1000

41

)

29

0010 1001

42

*

2A

0010 1010

43

+

2B

0010 1011

44

,

2C

0010 1100

45

-

2D

0010 1101

46


...
C, 192–193

& (ampersand), do-while loops, 227

& (AND) bitwise operator, 344

&& logical operator, 180

<> (angle brackets), 13

* (asterisk)


comments and, 56

as multiplication sign, 88, 134, 313

\ (backslash)

\’ (apostrophe), printf() escape

sequence, 307

\” (double-quote), printf() escape

sequence, 307

\0 (null), printf() escape sequence,

307

\? (question mark), printf() escape

sequence, 307

escape sequences, 45

printf() escape sequence, 307

RULES
...
C, 203–204
location, 322–323
variables, 320–321
#define directive, 104–105, 302–303

#else, 303

#endif, 303

#if, 303

#ifdef, 303

#ifndef, 303

#include


construction, 294–297
description, 30

<< (shift bits left) bitwise operator, 344

>> (shift bits right) bitwise operator, 344

/ (slash)

with asterisk ( /*), 56

division symbol, 87, 134, 313

double ( // ), 60, 63

// (double slash)

C++ comments, 60

nested comments and, 63


• A •

\a, printf() escape sequence, 306

abs() function, 319


absolute value of numbers, 320

acos() function, 319

addition symbol (+), 87


378

C For Dummies, 2nd Edition
alphabet trivia, 172

ampersand (&)

do-while loops, 227

pointers, 343

AND (&) bitwise operator, 344

AND logical operator

code example, 183

introduction, 180

angle brackets (< >), 13

arguments, 277, 282

arrays, 339–340, 341

ASCII characters

character variables, 129

extended codes, 129

table, 371–375

typing in, 122

ASCII
...
C, 140–141

assigning pointers, 343

assignment operators, 212

asterisk (*), comments and, 56

atan() function, 319

atoi() function

HEIGHT
...
C, 37–38

text strings, 31

backward counting loops, 205

BASIC programming language, 10

BCPL (Basic Combined Programming

Language), 10

BIGJERK1
...
C, 256–260

BIGJERK3
...
C, 277–278

binary numbers, integers and, 112

binary operators, 344

bitwise operators, 182, 344

blank lines in code, 14

BLOWUP1
...
C

dual variables, 267

global variable, 271–272

variables, 265–267

bonus() function, 288–289

BONUS
...
C, 236

bounds checking, do-while loops, 229–230

brackets ([]), single-character

variables, 123

break command, 244, 352

break keyword, 198–199

for (;;) loops, 237

case statements, 243

do-while loops, 228

nested loops, 235–237

break statements, while loops, 221

breaking loops, 197–198

breakpoints, 356

bugs, 27

bulletproofing, 229

bytes, 128


• C •

%c conversion character, printf()


function, 311

calling functions, 254, 279–280

caret (^) symbol, 316

case keyword, 244, 247

case sensitivity

else keyword, 159

function naming, 264

include directives, 296

keywords, 33

printf(), 42

source code, 13

case statement, 243, 244, 247

cat command, 351

cd command, 351

char keyword

introduction, 50

numeric data types, 108

single-character variables, 122–123

string variable declaration, 57

unsigned char keyword, 109

variable declaration, 40, 123–124

character data types, 108

character variables

char keyword, 121

characters in, 124


Index
as integer, 111

quotes, 123

value assignment, 124

as values, 128–129

characters

comparing, 166

conversion, 46

clear command, 350

cls command, 350

code
...
C, 51–52

command line, 345, 347

command prompt

commands, 350–351

IDE and, 350

commands

cat, 351

cd, 351

clear, 351

cls, 351

command prompt, 350–351

del, 351

dir, 351

exit, 351

if, 147–148

line numbers, text editor, 349

ls, 351

nv, 351

pwd, 351

ren, 351

return, 31

rm, 351

switch, 243

type, 351

comments

/* (slash with asterisk), 56

C++, 60

compiler and, 55

disabling statements, 61

introduction, 55

MADLIB1
...
C, 167–168

if keyword, 150–151


operators, 151–152

strings, if keyword and, 174

compiler

comments and, 55

errors, 27

FreeBSD, 360

GCC compiler, 15, 360, 365–367

GOODBYE
...
C, 40–41

conditions

do-while loops, 227

infinite loops, 196

const keyword, 106

constants

defining, 101–102

definition, 91

numeric, 101

numeric, shortcut, 102–104

semicolons, 269

string constants, 53, 101

symbolic, 103

variables and, 101

contents of variables, 76

context-colored text editors, 348–349

continue keyword

loops, 237–238

nested loops, 235–236

conversion characters

formatting strings, 46

printf() function, 311–312

converting, string numbers to integer
value, 81–82

379

380

C For Dummies, 2nd Edition
cos() function, 319

COUNTDOWN
...
C, 43

dead_horse variable, 223

debugging

order, 354

tools, 357

declaring arrays, 340

declaring functions, 263

declaring pointers, 343

declaring variables

float, 113

global, 270–271

integer variables, 110–111

introduction, 40

location in program, 95

multiple, 100–101

reasons for, 94–95

values as, 276

DECODD
...
See also incrementation

-- operator, 207–208, 322

assignment operators, 212

for loops, 206–207

introduction, 204–205

operator shortcuts, 212

skipping values, 210

default statements, switch structure, 244

defining functions, 263

del command, 351

delay() function, prototyping, 269

delay loops, 233

development cycle, 11

dir command, 350

disabling statements, comments and, 61

disk access, 345

displaying text, printf() and, 306

division symbol ( / ), 87


do keyword, 227

dot notation, structures, 342

do_this statement, for loop, 189

double keyword, numeric data types, 109

double quotes
...
C, 42–43

formatting strings, 46

strings, 42–43

double slash (//), 60

double variables

double precision numbers, 118

pow() function, 316

double-precision data types, 109, 118

do-while loops

& (ampersand), 227

bounds checking, 229–230

break keyword, 228

conditions, 227

execution, 227

input bounds, 229–230

introduction, 186

number checking, 229–231

semicolons, 227

statements, 227

dropBomb() function, 265–266

dual variables, BOMBER
...
C, 22–27

errors

bugs, 27

compiler errors, 27

critical errors, 25

fatal errors, 25

linker and, 26

linker errors, 27

null pointer assignment, 27

parse errors, 23

source code, 22–27

syntax errors, 23

escape clause, loops, 197

escape sequences, printf(), 44–45,

306–308

execute

definition, 160

do-while loops, 227

exit command, 351

exp() function, 319

exponents, math operations, 314–315

extended ASCII codes, 129


• F •

%f conversion character, printf()


function, 311

\f, printf() escape sequence, 306


fatal errors, 25

fflush() function, 170–171

file size, 346

filenames, extensions, 13

files

folders, 361–362

header files, # include and, 294–297

source code, 12

text, size, 262

flexibility of C, 222–223

float keyword

format, 113

numeric data types, 109

float variable, declaring, 113

floating-point values

double keyword, 118

formatting, 119–120

JUPITER
...
C, 148–150
GENIE2
...
C, 163–164
getchar() function
reading text from keyboard, 126

returning values, 283

returns, 168

single character reading, 171

standard input and, 168

gets() function

INSULT1
...
C

compiling, 15–16

creating, 13–14

recompiling, 21–22

running program, 16

typing tips, 14

goto keyword, loops, 186

greater than (>) comparison operator,

if statement, 152

greater than or equal to (>=) comparison

operator, if statement, 152

GREATER
...
C, 234–235


•H•

...
H, 297–298

writing, 298–299

HEAD
...
C, 135–136

HEY
...
C, 98–99


IDE (Integrated Development

Environment), command prompt
window, 350

if command
...
C, 173–174

comparisons and, 148, 150–151

introduction, 147–148

logical operators, 180–182

math and, 148

operators, 151–152

parentheses, 150

selection statements, 148

string comparison, 174

TAXES
...
C, 321

incrementation
...
C, 140–141

assignment operators, 212

five count, 211

for loops and, 188

introduction, 137

LARDO
...
C, 195

while loops, 217


input

functions, 275

getchar() and, 168

GREATER
...
H, 297–298

input bounds, do-while loop number
checking, 229–230
INSULT1
...
C, 69–70

int data types, 108

int integer, 110–111

int keyword

main() function and, 79


numeric data types, 108

placement in program, 78

range, 78

unsigned int keyword, 109

int main, 31

integers

binary numbers and, 112

floating-point number format, 119–120

versus floating-point numbers, 110

int, 110–111

introduction, 78–79

long int, 110–111

METHUS1
...
C

getval() function, 284–285


type-casting and, 286


• J •

jerk() function, 256–258, 278–279
JUPITER
...
C, 47–49

•K•

keyboard

numeric values, 81

reading text from, 125–126

reading text to, 127–128


383

384

C For Dummies, 2nd Edition
keyboard overflow, 67

keywords

break, 198–199

break, nested loops and, 235–237

case, 244

case sensitivity, 33

char, 50, 108

const, 106

continue, 235–236, 237–238

do, 227

double, 109

float, 109, 113

goto, 186

if, 148

int, 78, 108

introduction, 32

long, 109

return, 285–287

short, 108

short int, 108

struct, 341–342

switch, 243–244

unsigned char, 109

unsigned int, 109

unsigned long, 109

unsigned short, 109

variable naming and, 96

while, 218

kitty variable, 76–77

•L•
languages, high-level, 10

LARDO
...
C, 316–317

LIGHTS2
...
C, 240–243

LOBBY2
...
See also for loops

100
...
C, 187–188

stopping, 193–195, 197–198

switch-case, 239–247


Index
variable initialization, 217

while, 186, 215–216

lowercase text, 13, 33

low-level programming languages, reasons

to use, 10

ls command, 350

Lvalue errors, math, 314


• M •

Mac

compiler, 361

folders, 362

Mac OS X

compiler, 360

folders, 362

machine language, 10

macros, 303–304

MADLIB1
...
H header, pow() function, 315

MDAS mnemonic, 142–143

METHUS1
...
C, 83–85

METHUS3
...
C, 88–90


METHUS5
...
C, 36–37


naming

functions, 263–264

variables, 95

variables, calling functions and, 279–280

variables, guidelines, 95–96

variables, tips for, 351

negative numbers

E notation, 117

floating-point, 112

integers, 111

numeric data types, 111–113

nested comments, problems with, 62–63
nested loops

break keyword, 235–237

continue keyword, 235–236, 237–238

definition, 231

for loops, 233

GRID
...
C, 204

operating system interaction, 345

operators

-- (decrement), 207–208, 322

++ (incrementation), 202–203

binary, 344

bitwise, 344

comparison operators, 151–152

comparison operators with if

statement, 160

description, 34

if comparisons, 151–152

logical, 178

mathematical, + (addition), 134

mathematical, / (division), 134

mathematical, * (multiplication), 134

mathematical, - (subtraction), 134

shortcut for math, 212

optimizers, 357–358

OR (&) bitwise operator, 344

OR logical operator

examples, 181

if command and, 178


order of precedence

DENTIST
...
C, 144–145

OS (operating system), 27

OUCH
...
H, 297–298


• P •

PacMan example of variables, 76

parameters, functions, 279

parentheses

empty, 31

for keyword, 189, 190

functions, 254, 262

if command, 150

order of precedence and, 144, 145–146

source code, 13

statements, 34

strings, 31, 42

switch-case loops, 247

parse errors, 23

passing values, to functions, 279–282

PELLETS
...
H header, 315

pre-incrementing, 322–323, 351

precedence
...
C, 307–309
printing
text, 42–44
variables, 70
procedures, functions and, 253
program size, 346
programmer, 11
programming
breaking up code, 354

breakpoints, 356

talking through program, 355

programming code
...
C, 261–262
delay() function, 269
introduction, 258–259
semicolons, 260
value returning and, 283
pseudorandom numbers, 328
putchar() function, reading text to
keyboard, 127–128
puts() function
INSULT1
...
C, 69–70
introduction, 67
printf() function and, 71
STOP
...
See also double quotes
char variable, 123
formatting strings, 46
strings, 42–43

•R •
\r, printf() escape sequence, 306
rand() function

introduction, 326–328
seeds, 328–329
RAND_MAX, value, displaying, 330
random numbers
introduction, 325–326
pseudorandom numbers, 326
seeding, 326, 328–329
random-sampler variable program, 98–99
RANDOM1
...
C, 329–330
RANDOM3
...
C, 335–336
ranges
floating-point numbers, 114

int integer, 111

long int integer, 111

numeric data types, 108–109

reading text
from keyboard, 125–126
to keyboard, 127–128
recompiling source code, 21–22
ren command, 350
reserved words, 33
...
C, 288–289
returning values
atoi() function, 283

functions, 255, 282–289

getchar() function, 283

main() function and, 287–288

Ritchie, Dennis, 11
rm command, 351
RULES
...
C and, 51–52


format, 49

introduction, 40

null pointer assignment errors and, 51

reading text from keyboard, 125–128

string variables, 49

scientific notation

E notation, 116–117

introduction, 115

seeding random numbers, 326, 328–329
seedrnd() function, 329–331
selection statements
if keyword and, 148

switch-case loops, 241

semicolons

case statement, 247

compilers and, 31

constants, 269

do-while loops, 227

else keyword, 159

errors and, 24

gets(), 66

if test, 150

prototypes, 260

variable declaration, 276

while keyword, 219

shell command, 345

short int keyword, numeric data

types, 108

short keyword

numeric data types, 108

unsigned short keyword, 109

shortcuts for math operations, 212

signed numeric data types, 111–113

sin() function, 319

single quotes, char variable, 123

single-character variables, 122–123

single-line comments, 59

single-precision data types, 109

slash (/)

with asterisk ( /*), 56

double (//), 60

sleep() function, 234

source code

blank lines, 14

case sensitivity, 13

coding programs, 12

compiler and, 14–15

editing, 19–21, 24–25

errors, 22–27

filename extensions, 13

files, 12

header files, 300


indents, 14

linker, 15

parentheses, 13

recompiling, 21–22

saving, 16

text editors, 12

tweaking, 20

twiddling, 20

typing tips, 14

special characters, printf() function,
306

SPEED
...
H, 31, 297–298

STDLIB
...
C, 68

string constants

#define directive and, 105

description, 53, 101

string variables

description, 94

scanf() and, 49, 57

strings

comparing with if keyword, 174

description, 32, 340–341

formatting strings, 46

functions and, 42

gets() function, 66–67

literal strings, 53

NULL character, 341

number conversion to integer value,

81–82

numbers and, 82

parentheses, 31, 42

printing, 42–44

struct keyword, 341–342

Index
structures, 341–342

styles of comments, 58–60

subtraction symbol (-), 87

switch command, 243, 247

switch keyword, 243–244

switch-case loops

break command, 244–245

case keyword, 244

case statements, 244

default statements, 244

introduction, 239

LOBBY1
...
C, 155–157


text

display, printf(), 306

formatting, 47–49

justified, 47–49

lowercase, 13

printing, 42–44

puts() function, 67, 71

reading from keyboard, 125–126

reading to keyboard, 127–128

strings, 32

text editors

context-colored, 348–349

line-number commands, 349

running, 364–365

source code, 12

windows, 348

text files

size, 262

source code, 12

text strings, 31

time() function, 332

tweaking source code, 20

twiddling source code, 20

type command, 351

TYPER1
...
C, 220–222

typing, source code, 14


•U•
%u conversion character, printf()

function, 311

underline, variable naming and, 96

Unix, compiler, 361

unsigned char keyword, numeric data

types, 109

unsigned character data types, 109

unsigned int keyword, numeric data

types, 109

unsigned integer data types, 109

unsigned long keyword, numeric data

types, 109

unsigned numeric data types, 111–113

unsigned short keyword, numeric data

types, 109


•V•
\v, printf() escape sequence, 307


values

absolute, 320

arrays, 340

constants, 91

declaring as variables, 276

floating-point, 99

functions, returning, 282–289

functions, sending to, 276–277

if keyword, 165

incrementation, 138

keyboard entry, 81

mathematical operators, 134

numbers and, 82

numeric variables and, 80–81, 97

parameters, 279

passing multiple to functions, 280–282

passing to functions, 279

predefining in variables, 124

return keyword, 285–287

returning from functions, 255

returning, main() function and, 287–288

variables, 96–98

variables, char, 124

variables

++ operator, 321

arrays, 339–340

BOMBER
...
C, 267

float variable, 113

floating-point values, 99

for loop, 191

global, 269

global, declaring, 270–271

initializing, loops and, 217

integer, declaring, 110–111

kitty (string variable), 76–77

local, 270

mathematical operators, 134

METHUS1
...
C, 129

while keyword, statements, 218

while loops

break statement, 221


controls, 216

do-while loops, 225–231

for loop comparison, 219–220

for (;;) loops and, 220–222

infinite loops, 217

introduction, 186

nested, 233

overview, 215–216

repeat rate, 216

switch-case structure and, 248–250

while true condition, 218–219
while_true statement

for loops, 189

while loop, 218

WHORU
Title: Learn C for Dummies
Description: Notes to Learn C for Dummies - Very Simple and Easy - 411 pages