C For Dummies, 2nd Edition

Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man
logo, A Reference for the. Rest of Us! ... It became the world's fastest-selling
computer book, at one time moving more .... Part III: Giving Your Programs the
Ability.

Dan Gookin has been writing about technology for 20 years. He has contributed articles to numerous high-tech magazines and written more than 90 books about personal computing technology, many of them accurate. He combines his love of writing with his interest in technology to create books that are informative and entertaining, but not boring. 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. Perhaps Dan’s most famous title is the original DOS For Dummies, published in 1991. 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). That book spawned the entire line of For Dummies books, which remains a publishing phenomenon to this day. 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 pub­ lishes a free weekly computer newsletter, “Weekly Wambooli Salad,” full of tips, how-tos, and computer news. He also maintains the vast and helpful Web page www.wambooli.com. Dan holds a degree in communications and visual arts from the University of California, San Diego. He lives in the Pacific Northwest, where he enjoys spending time with his four boys in the gentle woods of Idaho.

Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/. Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development

to Run Amok ............................................................131 Chapter 11: C More Math and the Sacred Order of Precedence ..............................133 Chapter 12: C the Mighty if Command.......................................................................147 Chapter 13: What If C==C? .............................................................................................165 Chapter 14: Iffy C Logic..................................................................................................175 Chapter 15: C You Again ................................................................................................185 Chapter 16: C the Loop, C the Loop++ .........................................................................201 Chapter 17: C You in a While Loop...............................................................................215 Chapter 18: Do C While You Sleep................................................................................225 Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’...................................................239

Part V: Part of Tens ..................................................337 Chapter 27: Ten More Things You Need to Know about the C Language................339 Chapter 28: Ten Tips for the Budding Programmer...................................................347 Chapter 29: Ten Ways to Solve Your Own Programming Problems .........................353

Appendix A: The Stuff You Need to Know before You

Read All the Other Stuff in This Book.........................359 Appendix B: ASCII Table ...........................................371 Index .......................................................................377

Table of Contents

Introduction ..................................................................1 “What Will Understanding C Do for Me?”......................................................1 About This Here Dummies Approach............................................................2 How to Work the Examples in This Book ......................................................2 Foolish Assumptions .......................................................................................3 Icons Used in This Book..................................................................................3 What’s New with This Edition?.......................................................................4 Final Thots ........................................................................................................4

Chapter 6: C More I/O with gets() and puts() . . . . . . . . . . . . . . .65 The More I Want, the More I gets() ...........................................................65 Another completely rude program example.....................................66 And now, the bad news about gets()...............................................67 The Virtues of puts() ...................................................................................67 Another silly command-prompt program .........................................68 puts() and gets() in action.............................................................68 More insults ..........................................................................................69 puts() can print variables .................................................................70

Table of Contents Assigning values to numeric variables ..............................................80 Entering numeric values from the keyboard ....................................81 The atoi() function ............................................................................81 So how old is this Methuselah guy, anyway?....................................83 You and Mr. Wrinkles ...........................................................................85 A Wee Bit o’ Math ...........................................................................................86 Basic mathematical symbols ..............................................................86 How much longer do you have to live to break the

Methuselah record?..........................................................................88 Bonus modification on the final Methuselah program! ...................90 The direct result ...................................................................................91

floating-point? .................................................................................110 Integer types (short, long, wide, fat, and so on) ............................110 Signed or unsigned, or “Would you like a minus sign

with that, Sir?”.................................................................................111 How to Make a Number Float .....................................................................113 “Hey, Carl, let’s write a floating-point number program!” .............114 The E notation stuff............................................................................116 Bigger than the Float, It’s a Double! ...........................................................118 Formatting Your Zeroes and Decimal Places............................................119

C For Dummies, 2nd Edition Reading and Writing Single Characters .....................................................125 The getchar() function ...................................................................126 The putchar() function ...................................................................127 Character Variables As Values....................................................................128

Part III: Giving Your Programs the Ability

to Run Amok .............................................................131 Chapter 11: C More Math and the Sacred Order of Precedence . . .133 An All-Too-Brief Review of the Basic C Mathematical Operators ..........133 The old “how tall are you” program.................................................135 Unethical alterations to the old “how tall are you” program .......136 The Delicate Art of Incrementation (Or, “Just Add One to It”) ..............137 Unhappily incrementing your weight ..............................................138 Bonus program! (One that may even have a purpose in life).......140 The Sacred Order of Precedence ...............................................................141 A problem from the pages of the dentistry final exam..................141 What’s up, Sally?.................................................................................142 The confounding magic-pellets problem.........................................144 Using parentheses to mess up the order of precedence...............145

Chapter 12: C the Mighty if Command . . . . . . . . . . . . . . . . . . . . . . . . .147 If Only. . . .......................................................................................................147 The computer-genie program example ...........................................148 The if keyword, up close and impersonal .....................................150 A question of formatting the if statement .....................................154 The final solution to the income-tax problem ................................155 If It Isn’t True, What Else? ...........................................................................157 Covering all the possibilities with else ..........................................158 The if format with else ...................................................................159 The strange case of else-if and even more decisions ...............160 Bonus program! The really, really smart genie...............................163

with elegant while loops...............................................................220 C from the inside out .........................................................................222 Not to Beat a Dead Horse or Anything. . . . ...............................................223

Chapter 21: Contending with Variables in Functions . . . . . . . . . . . . .265 Bombs Away with the BOMBER Program! ................................................265 Will the dual variable BOMBER.C program bomb? ........................267 Adding some important tension.......................................................267 How We Can All Share and Love with Global Variables...........................269 Making a global variable....................................................................270 An example of a global variable in a real, live program ................271

Table of Contents Chapter 22: Functions That Actually Funct . . . . . . . . . . . . . . . . . . . . . .275 Marching a Value Off to a Function............................................................275 How to send a value to a function....................................................276 An example (and it’s about time!) ....................................................277 Avoiding variable confusion (must reading) ..................................279 Sending More than One Value to a Function.............................................280 Functions That Return Stuff........................................................................282 Something for your troubles.............................................................282 Finally, the computer tells you how smart it thinks you are ........284 Return to sender with the return keyword ...................................285 Now you can understand the main() function ..............................287 Give that human a bonus!..................................................................288 No Need to Bother with This C Language Trivia

If You’re in a Hurry ...................................................................................289

You Read All the Other Stuff in This Book ...................359 Setting Things Up .........................................................................................359 The C language compiler...................................................................360 The place to put your stuff................................................................361 Making Programs .........................................................................................363 Finding your learn directory or folder...........................................363 Running an editor...............................................................................364 Compiling and linking ........................................................................365

elcome to C For Dummies, 2nd Edition — your last, desperate, and final attempt to understand the C programming language.

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. Be able to write C programs that no other publisher would let an author print in its C books. 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.” Have fun. I can’t really guarantee that last point. However, this book was written minus the sword of mathematics hanging over anyone’s head. 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. Serious work is for the nerds. Fun happens when you read C For Dummies, 2nd Edition.

“What Will Understanding C Do for Me?”

Look at your computer screen. Imagine something happening there. Anything. As long as you know how to program a computer, what you imagine will take place. Okay, maybe not as fast as you like — but it can be done. Programming is the ultimate way to get even with a computer. You are in charge. You tell the beast what to do. And it will obey you, even when you tell it to do something stupid. Computers are fast and obedient, not smart.

2

C For Dummies, 2nd Edition Anything your computer does, any devices it talks with or controls, can be manipulated by using a programming language and writing programs that pull the right levers. The C programming language has been crowned the best and most common way to program any personal computer. C may not be the easi­ est programming language to figure out, but it’s not the most difficult, either. It’s tremendously popular and well supported, which makes it a good choice.

About This Here Dummies Approach

Most programming books start out by assuming that you don’t know anything. The author may remember that for, oh, maybe two or three chapters. Then, after that initial pressure is off, there he goes! Chapter 4 is written not to teach you how to program, but, rather, to impress the author’s programming buddies back at college. So your learning journey ends with a whimper. You will not find that problem in this book. The best way to learn something is one piece at a time. With programming, I prefer to show you things by using small programs, tiny models, and quickto-type examples. 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. That’s because the pace stays the same throughout the book. I insist on it! This book also gets you started right away. When researching other books, I noticed that often the first program you have to type is not only several dozen lines long, but also nearly 50 pages into the book on average! In this book, you get started right away with a program example on Page 13. 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. That’s the way I figured out how to program a com­ puter. I sat down with Dr. David Lien’s Learning TRS-80 BASIC (Compusoft) and, 36 solid hours later, I finished. Then I slept. Then I did it again because I com­ pletely forgot everything, but remembered enjoying doing it the first time. Your first task is to read Appendix A. It tells you how to set up a C language compiler on your computer and get things all ready to work. Next, you need to know how to type stuff. This stuff looks like this: Here I go, typing some stuff. La, la, la.

Introduction Mostly, you type complete programs, consisting of several lines like the one before this paragraph. Type them all, and press Enter at the end of each line. Because this book is only so wide, however, occasionally you see a line split in two. 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.

When you see that, don’t type two lines. If you just keep typing, everything fits on one line on your screen. If you forget this advice, your programs mess up, so I toss in several reminders throughout this book whenever such a thing happens.

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. It can be just about any computer; this book is not specific to Windows. You’re pretty good with the computer. You understand things. You may even fix your own problems or help others with their problems. You know how to look things up on the Web, download stuff, and find things you need. You have a passing familiarity with your operating system’s command prompt or terminal window. This is important, and it’s explained in Appendix A. 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.

Something you should remember to do.

3

4

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

A healthy suggestion worthy of note.

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. This book represents a compilation of basic material from both books. And, by reading this book, you’ll have a broad, basic knowledge of the C language. Unlike the older books, this one is organized on a chapter-by-chapter level, not by lessons. Each chapter is self-contained and, where necessary, cross references to other chapters are included. Gone are the quizzes and tests. This book has no homework, per se. Alas, this book is only so big, and only so much ground could be covered, given this book’s gentle pace. 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). That book is for more experienced program­ mers, which is what you will become after reading this book.

Final Thots

Understanding how to use C is an ongoing process. Only a dweeb would say “I know everything about programming in C.” There are new things to be learned every day and different approaches to the same problems. Nothing is perfect, but many things are close. 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. Whatever. Ask yourself this question: Does my program run? Okay. Does it do what I want? Better. Does it meet their artifi­ cial standards? Who cares? I’ll be happy if your sloppy C program works. But keep this in mind: The more you learn, the better you get. You’ll discover new tricks and adapt your programming style to them.

Introduction This book has a companion Web page, replete with bonus material and all sorts of fun information: http://www.c-for-dummies.com

I hope that you enjoy the journey you’re about to begin. Crack your knuckles, power up that compiler, and prepare yourself for a few solid hours of eyeball frazzle. You’re going C programming!

5

6

C For Dummies, 2nd Edition

Part I

Introduction to C Programming

Y

In this part . . .

ou have never programmed anything in your life. The VCR? Forget it! On your microwave oven, you use the Popcorn and Add a Minute buttons. 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. If that’s you, get ready to turn your life around. Contrary to what you may believe, it’s nothing to program a computer. Anyone can do it. Programmers may carry themselves with an air of mysticism and treat their skills like priests performing sacred religious rites. Poppycock. Programming is painless. It’s easy. It’s fun. It’s now your turn to tell the computer exactly what to do with itself. In just a few pages, you will be programming your PC. It’s time to get even! Time to twist its arm and wait until it bellows “Uncle! UNCLE! ” Get ready to take charge.

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. That’s what makes computers unique in the pantheon of modern devices. 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. It’s easy.

This chapter introduces you to the basics of programming. Although it has some yabber-yabber and background information, the meat of the chapter involves creating, compiling, and running your first program. 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.

An Extremely Short and Cheap History of the C Language First, there was the B programming language. Then there was the C program­ ming language.

10

Part I: Introduction to C Programming

Stuff you don’t need to know about language levels Programming languages have different levels, depending on how much they resemble human languages. Programming languages that use common words and are relatively easy for most folks to read and study are called highlevel languages. The opposite of those are low-level languages, which are not easy to read or study. High-level languages include the popular BASIC programming language as well as other lan­ guages that just aren’t that popular any more. BASIC reads almost like English, and all its com­ mands and instructions are English words — or at least English words missing a few vowels or severely disobeying the laws of spelling. The lowest of the low-level programming lan­ guages is machine language. That language is the actual primitive grunts and groans of the microprocessor itself. Machine language con­ sists of numbers and codes that the micro­ processor understands and executes. Therefore, no one really writes programs in machine lan­ guage; rather, they use assembly language, which is one step above the low-level machine

language because the grunts and groans are spelled out rather than entered as raw numbers. 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. Plus, the size of the program is smaller. A program written in Visual Basic may be 34K in size, but the same program written in assembly language may be 896 bytes long. On the other hand, the time it takes to develop an assembly language program is much longer than it would take to write the same program in a higher-level lan­ guage. It’s a trade-off. The C programming language is considered a mid-level language. 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. In C, you get the best of the high-level programming languages and the speed of development they offer, and you also get the compact program size and speed of a low-level language. That’s why C is so bitchen.

No, I’m not being flip. C was developed at AT&T Bell Labs in the early 1970s. At the time, Bell Labs had a programming language named B — B for Bell. The next language they created was C — one up on B. C is the offspring of both the B programming language and a language named BCPL, which stood for Basic Combined Programming Language. But you have to admit that the B story is cute enough by itself. You would think that the next, better version of C would be called the D language. But, no; it’s named C++, for reasons that become apparent in Chapter 16. C is considered a mid-level language. See the nearby sidebar, “Stuff you don’t need to know about language levels,” for the boring details.

Chapter 1: Up from the Primordial C The guy who created the C programming language at Bell Labs is Dennis Ritchie. I mention him in case you’re ever walking on the street and you happen to bump into Mr. Ritchie. 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.” And you can say “Cool.”

The C Development Cycle Here is how you create a C program in seven steps — in what’s known as the development cycle: 1. Come up with an idea for a program. 2. Use an editor to write the source code. 3. Compile the source code and link the program by using the C compiler. 4. Weep bitterly over errors (optional). 5. Run the program and test it. 6. Pull out hair over bugs (optional). 7. Start over (required). No need to memorize this list. It’s like the instructions on a shampoo bottle, though you don’t have to be naked and wet to program a computer. Eventually, just like shampooing, you start following these steps without thinking about it. No need to memorize anything. The C development cycle is not an exercise device. In fact, program­ ming does more to make your butt fit more snugly into your chair than anything. Step 1 is the hardest. The rest fall naturally into place. Step 3 consists of two steps: compiling and linking. For most of this book, however, they are done together, in one step. Only later — if you’re still interested — do I go into the specific differences of a compiler and a linker.

From Text File to Program

When you create a program, you become a programmer. 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.

11

12

Part I: Introduction to C Programming As a programmer, you job is not “programming.” No, the act of writing a pro­ gram is coding. So what you do when you sit down to write that program is code the program. Get used to that term! It’s very trendy. The job of the programmer is to write some code! Code to do what? And what type of code do you use? Secret code? Morse Code? Zip code? The purpose of a computer program is to make the computer do something. The object of programming is to “make it happen.” The C language is only a tool for communicating with the PC. 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. And if you can’t give them what they want, at least make it close enough so that they don’t constantly com­ plain or — worse — want their money back. The tool you have chosen to make it happen is the C programming language. That’s the code you use to communicate with the PC. The following sections describe how the process works. After all, you can just pick up the mouse and say “Hello, computer!” Programming is what TV network executives do. Computer programmers code. You use a programming language to communicate with the computer, telling it exactly what to do.

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. To create a PC epistle, you use a program called a text editor. This program is a primitive version of a word processor minus all the fancy formatting and print­ ing controls. The text editor lets you type text — that’s about all. Using your text editor, you create what’s called a source code file. The only spe­ cial thing about this file is that it contains instructions that tell the computer what to do. 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. In this case, the instructions are written in the C language.

Chapter 1: Up from the Primordial C The source code file is a text file on disk. The file contains instructions for the computer that are written in the C programming language. You use a text editor to create the source code file. See Appendix A for more information on text editors.

Creating the GOODBYE.C source code file

Use your text editor to create the following source code. Carefully type each line exactly as written; everything you see below is important and necessary. Don’t leave anything out: #include 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. You recognize some words (include, main, “Goodbye, cruel world!”, and return), and some words look strange to you (stdio.h, printf, and that \n thing). When you have finished writing the instructions, save them in a file on disk. Name the file GOODBYE.C. 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. See Appendix A for information on using a text editor to write C language programs as well as for instructions on where you should save the source code file on disk. In Windows Notepad, you must ensure that the file ends in .C and not in .TXT. Find a book about Windows for instructions on showing the file­ name extensions, which makes saving a text file to disk with a .C exten­ sion easier. Note that the text is mostly in lowercase. It must be; programming lan­ guages are more than case sensitive — they’re case-fussy. Don’t worry when English grammar or punctuation rules go wacky; C is a computer language, not English. Also note how the program makes use of various parentheses: the angle brackets, < and >; the curly braces, { and }; and the regular parentheses, ( and ).

13

14

Part I: Introduction to C Programming

Extra help in typing the GOODBYE.C source code The first line looks like this: #include

Type a pound sign (press Shift+#) and then include and a space. Type a left angle bracket (it’s above the comma key) and then stdio, a period, h, and a right angle bracket. Everything must be in lowercase — no capitals! Press Enter to end this line and start the second line. Press the Enter key alone on the second line to make it blank. Blank lines are common in pro­ gramming code; they add space that separates pieces of the code and makes it more readable. 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. Press Enter to start the fourth line. Type a left curly brace: {

This character is on a line by itself, right at the start of the line. Press Enter to start the fifth line.

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

If your editor was smart enough to automati­ cally indent this line, great. If not, press the Tab key to indent. Then type printf, the word print with a little f at the end. (It’s pronounced “print­ eff.”) Type a left parenthesis. Type a double quote. Type Goodbye, cruel world, followed by an exclamation point. Then type a backslash, a little n, double quotes, a right parenthesis, and, finally, a semicolon. Press Enter to start the sixth line. return(0);

If the editor doesn’t automatically indent the sixth line, press the Tab key to start the line with an indent. Then type return, a paren, 0 (zero), a paren, and a semicolon. Press Enter. On the seventh line, type the right curly brace: }

Some editors automatically unindent this brace for you. If not, use your editor to back up the brace so that it’s in the first column. Press the Enter key to end this line. Leave the eighth line blank.

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. This job is tackled by the compiler. 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.

Chapter 1: Up from the Primordial C If all goes well and the compiler is duly pleased with your source code, the compiler creates an object code file. It’s a middle step, one that isn’t necessary for smaller programs but that becomes vital for larger programs. Finally, the compiler links the object code file, which creates a real, live com­ puter program. If either the compiler or the linker doesn’t understand something, an error message is displayed. At that point, you can gnash your teeth and sit and stew. Then go back and edit the source code file again, fixing whatever error the compiler found. (It isn’t as tough as it sounds.) Then you attempt to compile the program again — you recompile and relink. The compiler translates the information in the source code file into instruc­ tions the computer can understand. The linker then converts that infor­ mation into a runnable program. The GCC compiler recommended and used in this book combines the compiling and linking steps. An object file is created by GCC, but it is automatically deleted when the final program file is created. Object code files end in OBJ or sometimes just O. The first part of the object file name is the same as the source code filename. Feel free to cheerfully forget all this object code nonsense for now. Text editor➪Compiler. Source code➪Program.

Compiling GOODBYE.C The gritty details for compiling a program are in Appendix A. Assuming that you have thumbed through it already, use your powerful human memory to recall the proper command to compile and link the GOODBYE.C source code. Here’s a hint: gcc goodbye.c -o goodbye

Type that command at your command prompt and see what happens. Well? Nothing happens! If you have done everything properly, the GCC compiler merely creates the final program file for you. The only time you see a mes­ sage is if you goof up and an error occurs in the program.

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. Very carefully review the source code earlier in this chapter and compare it with what you have written. Use the editor to fix your mistake, save the code to disk, and then try again. Note that GCC reports errors by line number, or it may even specifically list the foul word it found. In any event, note that Chapter 2 covers error-hunting in your C programs.

Running the final result

If you used the proper compiling command, the name of the program to run is identical to the first part of your source code. 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. Type this command: ./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.)

Save It! Compile and Link It! Run It!

Four steps are required in order to build any program in C. They are save, com­ pile, link, and run. Most C programming language packages automatically per­ form the linking step, though whether or not it’s done manually, it’s still in there. Save! Saving means to save your source code. You create that source code in a text editor and save it as a text file with the C (single letter C) extension.

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. The linking step is where the instructions are finally transformed into a program file. (Again, your compiler may do this step automatically.) Run! Finally, you run the program you have created. Yes, it’s a legitimate pro­ gram, like any other on your hard drive. You have completed all these steps in this chapter, culminating in the cre­ ation of the GOODBYE program. That’s how C programs are built. At this stage, the hardest part is knowing what to put in the source file, which gets easier as you progress through this book. (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. That’s because these steps are more or less mechanical. What’s more important is understanding how the language works. That’s what you start to find out about in the next chapter.

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.The fact is, most of your programming time is spent dealing with errors, from typos to flaws in logic. Those errors have to be fixed. It happens so often that one guru I know commented that the process should be called debugging and not programming.

This chapter gets you used to the idea of errors and how to deal with them. As you may note, it’s the second chapter of this book. That must mean that dealing with errors is a larger part of the programming picture than you may have otherwise imagined.

The Required Woes of Editing and Recompiling As a human, you may commit the vocal sin of pronouncing the t in often or adding an r after the a in Washington. Big deal! But just once, type pirntf rather than printf and your entire programming world becomes unglued. Or, worse, forget a curly brace. One missing curly brace can lead to a screen full of embarrassing error messages.

20

Part I: Introduction to C Programming Before you cower in shame, fear not, gentle programmer newbie person. Errors happen. You deal with them. Like this: 1. Reedit your source code, saving the fixed-up file to disk. 2. Recompile the source code. 3. Run the result. Errors can still happen. Heck, you may never get to Step 3! But these steps show you how to deal with them. It happens. I might remind you to look at the C language development cycle from Chapter 1. Note Steps 4 and 6. Nod your head wisely in agreement.

Reediting your source code file

Source code is not carved in stone — or silicon, for that matter. It can be changed. Sometimes, the changes are necessary, in the case of errors and boo-boos. At other times, you may just want to modify your program, adding a feature or changing a message or prompt — what the hard-core C geeks call tweaking or twiddling. To do that, you have to reedit your source code file. For example, the GOODBYE program from Chapter 1 displays a message on the screen: Goodbye, cruel world!

This program can easily be modified to show any message you like. To do so, use your editor and change the source code file, replacing the original mes­ sage with your newer, pithier message. Follow these steps: 1. Use your text editor to reedit the GOODBYE.C source code. 2. Edit Line 5, which looks like this: printf(“Goodbye, cruel world!\n”);

Change only the text between the double quotes. That’s the information that is displayed on the screen. Everything else — don’t touch!

Chapter 2: C of Sorrow, C of Woe 4. Double-check your work. 5. Save the file to disk. It’s okay to overwrite the original; your modified file becomes the new GOODBYE.C source code file. Now you’re ready to recompile your source code, as covered in the next section. “Reedit your source code file” means to use your text editor to modify the source code, the text file that contains the C language instructions. You reedit the source code file to repair an error caught by the compiler or linker or to modify the program. This situation happens a lot. 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). In this case, press the up-arrow key a few times until the original command to edit the GOODBYE.C source code file reappears at the prompt.

Recompiling (or the C equivalent of the “do-over”) Recompiling means to make the program one more time — to rework the steps you went through to create the program originally. This process usually hap­ pens after you modify or change the source code, such as you do in the pre­ ceding section. Because the source code is different, you have to feed it to the compiler again to generate the new, better (and, hopefully, bug-free) program. To recompile the new GOODBYE.C source code, use your compiler as outlined in Appendix A. For most everyone, that’s gcc goodbye.c -o goodbye

Press the Enter key and pray that no error messages appear, and then you’re done. The new program has been created. Run the program! Type the proper command — either goodbye or ./goodbye — at the prompt to see the new, stunning output. Who knew that it would be so darn easy to display such crap on the computer’s screen?

21

22

Part I: Introduction to C Programming After you reedit your source code file, you have to recompile to re-create the program file. That is how you fix an error or modify the program. If you’re programming in an IDE (Integrated Development Environment) such as Dev-C++ or Microsoft Visual C++, you may need to use a Rebuild or Rebuild All command to create a new program after modifying your source code. If you see any errors after recompiling, you must re-reedit your source code and then re-recompile again. (You only “reedit” and “recompile”; no sense in getting re-happy.)

Dealing with the Heartbreak of Errors

Errors happen. Even the best of programmers get errors, from the innocent code-writing cog at Microsoft to the sneering, snooty Linux programmer whose only contact with humanity is the pizza guy — they all get errors. Every day. Errors are nothing to be embarrassed about. Consider them learning tools or gentle reminders. That’s because the compiler tells you, with uncanny accu­ racy, just what the error is and where it is. 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. Yes, computers can be forgiving — and this can even teach you something.

Yikes! An error! But, before

you shoot yourself. . . . Here is a new program, ERROR.C. Note the optimism in its name. It’s a flawed C program, one that contains an error (albeit an on-purpose error): #include int main() { printf(“This program will err.\n”) return(0); }

Type the source code exactly as it appears here. Do not use the GOODBYE.C source code as a base; start over here with a clean editor window. When you’re done entering the source code, save it to disk as ERROR.C. Com­ pile it, and then. . . .

Chapter 2: C of Sorrow, C of Woe Unfortunately, when you compile this program, it produces an error. The next section provides the autopsy. 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 -o error

That’s the last compiling hint you get in this book!

The autopsy The ERROR.C program erred! What a shock. Don’t be alarmed — it was expected. (In fact, you may have seen this type of error before.) Here is a sample of what the cruel message may look like: error.c: In function `main’: error.c:6: parse error before “return”

How rude! It’s not that reassuring hand on your shoulder and the kind, avun­ cular voice explaining that you boo-booed. Still, what the error message lacks in personality, it makes up for in information. On the up side, though the error message is cryptic, it’s informative. 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.c The line that contains the error, Line 6 (though it may not be — you

can’t really trust computers too much)

The type of error, a parse error or syntax error or something similar The location of the error (before the word return) It still may not be clear exactly what’s wrong, but you’re given many clues. Most important, you’re given a line number: The error is in Line 6. Okay, it’s really in Line 5, but the C programming language is flexible, and the compiler doesn’t discover that “something’s missing” until Line 6. (You can cut the compiler some slack here.) The error type is also important. 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. In this case, a missing semicolon character at the end of Line 5 is to blame.

23

24

Part I: Introduction to C Programming The solution? You have to reedit the source code file and fix what’s wrong. In this case, you would reedit ERROR.C and add the semicolon to the end of Line 5. Even if you looked at Line 6 (per the output’s insistence), you would see nothing wrong there. 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. Errors are not the end of the world! Everyone gets them. Syntax refers to the way a language is put together. Some compilers use that term rather than parse, which means “the order in which things are put together.” Eh. Some versions of GCC put double quotes around “return” rather than the tick marks shown in the preceding example. Beyond that, GCC is remarkably consistent with its error messages. Missing semicolons are one of the most popular types of errors in the C language. You find out in the next chapter more about semicolons and the role they play. The error message’s line number refers to a line in the source-code text file. 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. The line number may or may not be accurate. In the case of a missing semicolon, the next line may be the “error line.” This statement holds true with other types of errors in C. Oh, well — at least it’s close and not a generic honk of the speaker and “ERRORS GALORE, YOU FOOL” plas­ tered onscreen. A good habit is to fix the first error listed and then recompile. Often, the first error is the only real one, but the compiler lists others that follow because it becomes confused. Of course, you may be thinking “Okay, smarty-pants computer, you know what’s wrong — fix it!” But computers don’t just jump to conclusions like that. That is the evil of the statement “Do what I mean”: Computers can’t read minds, so you must be precise. They are champs, however, at point­ ing out what’s wrong (and almost snobbishly so).

Repairing the malodorous program

To make the world right again, you have to fix the program. This process requires editing the source code file, making the needed correction, saving the source code file back to disk, and then recompiling.

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. Some compilers call the errors critical errors. (Sounds like a mistake Roger Ebert would make.) Other times, they’re fatal errors, like opening a creepy closet in one of those Scream movies. The warning error means “Ooo, this doesn’t look tasty, but I’ll serve it to you anyway.” Chances are, your program runs, but it may not do what you intend. Or, it may just be that the

compiler is being touchy. With most C compil­ ers, you can switch off some of the more per­ snickety warning error messages. The critical error means “Dear Lordy, you tried to do something so criminal that I cannot morally complete this program.” Okay, maybe it’s not that severe. But the compiler cannot complete its task because it just doesn’t under­ stand your instructions.

You can fix the ERROR.C program by adding a semicolon. Edit Line 5 and add a semicolon to the end of the line. Also correct the sentence displayed on the screen so that it reads as follows: printf(“This program will no longer err.\n”);

Other than changing Line 5, everything else in the program remains untouched. Save ERROR.C back to disk. Recompile the program and then run it: This program will no longer err.

Indeed, it does not! I can’t always tell you where to fix your programs. ERROR.C is the only program listed in this book that contains an on-purpose error. When you get an error message, you should check it to see where the error is in your source code. Then cross-check your source code with what’s listed in this book. That way, you find what’s wrong. But when you venture out on your own and experiment, you have only the error message to go by when you’re hunting down your own errors. Pull two Rs out of ERRORS and you have Eros, the Greek god of love. The Roman god of love was Cupid. Replace the C in Cupid with St and you have Stupid. Stupid errors — how lovely!

25

26

Part I: Introduction to C Programming

Now try this error!

Don’t dispense with the ERROR.C file just yet. Don’t close the window, and don’t zap the project. (If you did, use your editor to load the ERROR.C file and prepare to reedit.) Change Line 6 in the ERROR.C source code file to read this way: retrun(0);

In case you don’t see it, the word return has been mangled to read retrun; the second r and the u are transposed. Otherwise, the zero in the parentheses and the semicolon are unchanged. The way C works is that it just assumes that retrun is something you’re seri­ ous about and not a typo. The compiler couldn’t care less. But the linker goes nuts over it. That’s because it’s the linker that glues program files together. It catches the error when it doesn’t find the word retrun in any of its libraries. And, like any frazzled librarian, the linker spews forth an error message. Save the modified ERROR.C file to disk. Then recompile. Brace yourself for an error message along the lines of temporary_filename.o: In function ‘main’: temporary_filename.o: undefined reference to ‘retrun’

Or, the message may look like this: temporary_filename.o(blah-blah):error.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. In this case, the linker is explaining that the error is in reference to the word retrun. So, rather than use a line-number reference, you can always just search for the bogus text. To fix the error, reedit the source code and change retrun back to return. Save. Recompile. The linker should be pleased. As I mention elsewhere in this book, the GCC compiler both compiles and links. If the linker is run as a separate program, it obviously produces its own error messages. A temporary file is created by the compiler, an object code file that ends in .O — which you can see in the error message output. This object code file is deleted by GCC.

Chapter 2: C of Sorrow, C of Woe The linker’s job is to pull together different pieces of a program. If it spots something it doesn’t recognize, such as retrun, it assumes, “Hey, maybe it’s something from another part of the program.” So the error slides by. But, when the linker tries to look for the unrecognized word, it hoists its error flags high in the full breeze.

All about errors! A common programming axiom is that you don’t write computer programs as much as you remove errors from them. Errors are every­ where, and removing them is why it can take years to write good software. 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. These errors are the friendly ones, generally self-explanatory with line numbers and all the trimmings. The errors are caught before the program is built. Linker errors: Primarily involve misspelled com­ mands. 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. Also, if your linker requires some “library” file and it can’t be found, another type of error message is displayed. Pieces of the program are built, but errors pre­ vent it from them being glued together.

Run-time errors: Generated by the program when it runs. 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. (This happens often in C.) The most common run-time error is a null pointer assign­ ment. You aggravate over this one later. The program is built, but usually gets shut down by the operating system when it’s run. Bugs: The final type of error you encounter. The compiler diligently creates the program you wrote, but whether that program does what you intended is up to the test. If it doesn’t, you must work on the source code some more. Bugs include everything from things that work slowly to ones that work unintentionally or not at all. These are the hardest things to figure out and are usually your highest source of frustration. The program is built and runs, but it doesn’t behave the way you think it would.

27

28

Part I: Introduction to C Programming

Chapter 3

C Straight In This Chapter Looking at the C language Dissecting source code Obeying the RULES Using \n Splitting up lines with \

A

ny new language looks weird to you. Your native tongue has a certain cadence or word pattern. And the letters all fit together in a certain way. Foreign languages, they have weird characters: ç, ü, and ø and letter combi­ nations that look strange in English — Gwynedd, Zgierz, Qom, and Idaho.

Strange new things require getting used to. You need a road map to know what’s what. There’s really no point in blindly typing in a C program unless you have a faint idea of what’s going on. That’s what this chapter shows. After reading through two chapters and compiling two different C programs and dealing with the heartbreak of errors, this chapter finally and formally introduces you to the C language.

The Big Picture

Figure 3-1 outlines the GOODBYE.C program’s source code, which I use as an example in Chapter 1. Each program must have a starting point. When you run a program, the operat­ ing system (OS) sends it off on its way — like launching a ship. As its last dockmaster duty, the OS hurls the microprocessor headlong into the program. The microprocessor then takes the program’s helm at a specific starting point.

In all C programs, the starting point is the main() function. Every C program has one; GOODBYE.C, ERROR.C, and all the other C programs you ever create. The main() function is the engine that makes the program work. The main() function is also the skeleton upon which the rest of the program is built. main() is the name given to the first (or primary) function in every C pro­ gram. C programs can have other functions, but main() is the first one. In C, functions are followed by parentheses. The parentheses can be empty, or they can contain information — it all depends on the individ­ ual function. When I write about C language functions in this book, I include the paren­ theses, as in main(). A function is a machine — it’s a set of instructions that does something. C programs can have many functions in them, though the main() func­ tion is the first function in a C program. It’s required. Function. Get used to that word.

C Language Pieces’ Parts Here are some interesting pieces of the C program shown in Figure 3-1: 1. #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. What it does is tell the compiler to “include” text from another file, stuffing it right into your source code. Doing this avoids lots of little, annoying errors that would otherwise occur.

Chapter 3: C Straight 2. is a filename hugged by angle brackets (which is the C language’s attempt to force you to use all sorts of brackets and whatnot). The whole statement #include tells the compiler to take text from the file STDIO.H and stick it into your source code before the source code is compiled. The STDIO.H file itself contains information about the STanDard Input/Output functions required by most C programs. The H means “header.” You read more about header files in Chapter 23. 3. int main does two things. First, the int identifies the function main as an integer function, meaning that main() must return an integer value when it’s done. Second, that line names the function main, which also identifies the first and primary function inside the program. You find out more about functions returning values in Chapter 22. 4. Two empty parentheses follow the function name. Sometimes, items may be in these parentheses, which I cover in Chapter 22. 5. All functions in C have their contents encased by curly braces. So, the

function name comes first (main in Item 3), and then its contents — or

the machine that performs the function’s job — is hugged by the curly

braces.

6. printf is the name of a C language function, so I should write it as printf(). It’s job is to display information on the screen. (Because printers predated computer monitors, the commands that display infor­ mation on the screen are called print commands. The added f means “formatted,” which you find out more about in the next few chapters.) 7. Like all C language functions, printf() has a set of parentheses. In the parentheses, you find text, or a “string” of characters. Everything between the double quote characters (“) is part of printf’s text string. 8. An interesting part of the text string is \n. That’s the backslash character and a little n. What it represents is the character produced by pressing the Enter key, called a newline in C. You read more about this and other weird backslash-character combinations in Chapter 7. 9. The printf line, or statement, ends with a semicolon. The semicolon is C language punctuation — like a period in English. The semicolon tells the C compiler where one statement ends and another begins. Note that all statements require semicolons in C, even if only one statement is in a program or function. 10. The second statement in GOODBYE.C is the return command. This command sends the value 0 (zero) back to the operating system when the main() function is done. Returning a value is required as part of the main() function. You read why in Chapter 22. Note that even though this command is the last one in the program, this statement ends in a semicolon.

31

32

Part I: Introduction to C Programming Text in a program is referred to as a string. For example, “la-de-da” is a string of text. The string is enclosed by double quotes. A C language function starts with the function type, such as int, and then the function name and parentheses, as in main(). Then come a set of curly braces, { and }. Everything between the { and } is part of the function. The C language is composed of keywords that appear in statements. The statements end in semicolons, just as sentences in English end in periods. (Don’t frazzle your wires over memorizing this right yet.)

The C Language Itself — the Keywords

The C language is really rather brief. C has only 32 keywords. If only French were that easy! Table 3-1 shows the keywords that make up the C language.

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. Other words or instructions are called functions. These include jewels like printf() and several dozen other common functions that assist the basic C language keywords in creating programs. Beyond keywords, programming languages (like human languages) also involve grammar, or properly sticking together the words so that understandable ideas are conveyed. This concept is completely beyond the grasp of the modern legal community.

Chapter 3: C Straight

Even more keyword madness! Keywords are worth noting because their use is restricted or reserved. For example, you cannot think up your own function and name it short. That’s because short is a keyword, reserved only for its specific purpose in the core C lan­ guage. That’s one way the keywords are special. In addition to the 32 keywords shown in Table 3-1 are these two depreciated C language keywords: fortran entry C once had these keywords, but no longer. Still, I would avoid using them in your programs. (That’s what “depreciated” means.) Also, the C++ language has a hoard of reserved words. If you plan to study C++, include these

words in your do-not-use, reserved C language vocabulary: asm

false

private

throw

bool

friend

protected

true

catch

inline

public

try

class

mutable

reinterpret_cast typeid

const_cast

namespace static_cast

using

delete

new

virtual

dynamic_cast operator

template this

It’s better to know these words now and not use them than to use one (such as new or friend) and run into trouble later when you eventually find out how to use C++.

In addition to grammar, languages require rules, exceptions, jots and tittles, and all sorts of fun and havoc. Programming languages are similar to spoken language in that they have various parts and lots of rules. The keywords can also be referred to as reserved words. Note that all keywords are lowercase. This sentence is always true for C: Keywords, as well as the names of functions, are lowercase. C is case sen­ sitive, so there is a difference between return, Return, and RETURN. You are never required to memorize the 32 keywords. In fact, of the 32 keywords, you may end up using only half on a regular basis. Some keywords are real words! Others are abbreviations or combinations of two or more words. Still others are cryptograms of the programmers’ girlfriends’ names. Each of the keywords has its own set of problems. You don’t just use the keyword else, for example; you must use it in context.

33

34

Part I: Introduction to C Programming Functions such as printf() require a set of parentheses and lots of stuff inside the parentheses. (Don’t fret over this statement right now; just nod your head and smile in agreement, “Yes, printf() does require lots of stuff.”) By the way, the fact that printf() is a C function and not a keyword is why the #include thing is required at the beginning of a pro­ gram. The STDIO.H file contains instructions telling the compiler what exactly printf() is and does. If you edit out the #include line, the compiler produces a funky “I don’t know what to do with this printf() thing” type of error.

Other C Language Components

The C language has many other parts, making it look rather bizarre to the new programmer. Right now, all that’s standing between ignorance and knowledge is time, so don’t dwell on what you don’t know. 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. Included with the words are symbols. Sometimes these symbols are called operators, and at other times they’re called something else. For example, the plus sign (+) is used in C to add things. The words have options and rules about how they’re used. These rules are all referenced in the C reference material that came with your compiler. 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. Parentheses are used to group some of the important items required by C words. The words are put together to create statements, which are similar to sentences in English. The statements all end with a semicolon. Braces are used to group parts of a program. Some words use braces to group their belongings, and all the separate functions you create within a program are grouped by braces. 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. All this stuff put together (and more stuff I dare not discuss at this point) makes up the syntax of the C language. Syntax is how languages are put together.

Chapter 3: C Straight

Pop Quiz! 1. The core function in every C language program is called A. numero_uno(). B. main(). C. primus(). D. core(). 2. C language keywords are A. The “words” of the C language. B. Held together with string and earwax. C. Uttered only in candlelit reverence by the C Language Gurus. D. As numerous as the stars and nearly as distant. 3. In addition to keywords are A. Functions, such as printf(). B. Operators, such as +, -, and other weird things. C. Curly braces or brackets, angle brackets — all sorts of brackets. Man, do we have a bracket problem! D. Probably all of the above. 4. Functions require parentheses because A. They talk in whispers. B. The parentheses keep the function warm. C. The parentheses hold various things required by or belonging to the function. D. What’s a function? 5. A telltale sign of any C program is its curly braces. 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.

35

36

Part I: Introduction to C Programming

The Helpful RULES Program

I just can’t let you go without a program in this chapter. To help you under­ stand the most easily offended C rules, I have summarized them in the follow­ ing program. It displays several lines of text that remind you of the basic rules of C that you know about: #include 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.\ It’s a case-sensitive language.”); return(0); }

Type the preceding source code into your editor. Save the code to disk as RULES.C. Compile and run. 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. This program is really no different from those shown in previous chap­ ters. It merely has more printf() functions. The final printf() function (in Line 10) may seem a little odd. That’s because it’s split between two lines. This weird contraption is covered later in this chapter.

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. It’s a case-sensitive language.

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. You have seen it before. It’s that weird \n thing:

Chapter 3: C Straight \n

This line is C-speak for “Gimme a new line of text.” The n stands for new in new line (though they write it as one word: newline). The program you just created, RULES.C, needs the \n character at the end of each line to ensure that each line is displayed on a line by itself on the screen. This addition makes the output of the RULES program easy to read. Edit the RULES.C source code file again. Before the last double-quote in each printf() string, add the \n newline character.

If you’re good with search and replace, search for the “) (quote-paren) and replace it with \n”). Save the file to disk and recompile it. 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. It’s a case-sensitive language.

In C, the \n character is used in a text string as though the Enter key were pressed. It’s always \n with a little n. C is mostly lowercase. The \n is called newline, though calling it “slash-n” or “backslash-n” is acceptable as long as you don’t say it aloud. Table 24-1, in Chapter 24, lists other characters of a similar nature to \n.

Breaking up lines\ is easy to do Another anomaly of the RULES program is that rogue \ character found at the end of the tenth line. 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. So, these two lines: printf(“C is done mostly in lowercase\ It’s a case-sensitive language.\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.\n”);

37

38

Part I: Introduction to C Programming You may find such a trick necessary for extra-long lines as your programs grow more complex. The \ simply lets you split up a long line between several lines in your source code. That can be handy. 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. For example, the output on your screen may look like this: 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. sensitive language.

It’s a case-

That happens because the split line includes a few tabs to indent things — which looks pretty in your source code, but looks like blech when the pro­ gram runs. The solution is merely to edit the source code so that the extra tabs are removed from the string of text. To wit, change Lines 10 and 11 in the source code from this: printf(“C is done mostly in lowercase.\ It’s a case-sensitive language.”);

to this: printf(“C is done mostly in lowercase. \ It’s a case-sensitive language.”);

Note the extra space after the period in the first line (before the backslash), which keeps the two lines of text from running into each other. Save that mess. Compile and run. The output shall be most pleasing to the eye. Do note that some programs elsewhere in this book may use the \ to split long lines. Don’t worry about using the \ to split any lines. It’s a trick you see others use occasionally, but in my travels I prefer using a sideways-scrolling editor to splitting up long 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. So, if a semicolon were missing at the end of Line 11 in the RULES.C example, the compiler would flag it on that line, not on the line before it.

omputers are all about input and output — the old I/O of days gone by, what the pioneers once sang about. The wimminfolk would want to dance real slow. Maybe cry. It was a sentimental thing, y’all — something that fancy, dooded-up city slickers read about in dime magazines. A-hem! Input and output: You type something in and get a response, ask a question and get an answer, put in two dollars in coins and get your soda pop — things along those lines. This goes along with what I present in Chapter 3: It is your job as a programmer to write a program that does something. At this point in the learning process, triviality is okay. Soon, however, you begin to write pro­ grams that really do something.

Introduce Yourself to Mr. Computer

To meet the needs of input and output — the old I/O — you can try the follow­ ing program, WHORU.C — which is “who are you” minus a few letters. Please don’t go calling this program “horror-you” (which could be spelled another way, but this is a family book).

40

Part I: Introduction to C Programming The purpose of this program is to type your name at the keyboard and then have the computer display your name on the screen, along with a nice, friendly greeting: #include int main() { char me[20]; printf(“What is your name?”); scanf(“%s”,&me); printf(“Darn glad to meet you, %s!\n”,me); return(0); }

Don’t bother with any details just yet. Type and hum, if it pleases you.

Save the file to disk. Name it WHORU.C.

Don’t compile this program just yet. That happens in the next section.

The char me[20]; thing is a variable declaration. It provides storage for the information you enter (the I in I/O). You find out more about variables in Chapter 8. The new function here is scanf(), which is used to read input from the keyboard and store it in the computer’s memory. Left paren is the ( character. Right paren is the ) character. Paren is short for parenthesis or a type of steak sauce. (It’s also not a “real” word and is frowned on by English teachers of the high-and-tight bun.)

Compiling WHORU.C

Compile the WHORU.C source code. If you see syntax or other errors, doublecheck your source code with what is listed in this book. Ensure that you entered everything properly. 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. If you need to fix any errors, do so now. Otherwise, keep reading in the next section.

Chapter 4: C What I/O Refer to Chapter 2 for more information on fixing errors and recompiling. A common beginner error: Unmatched double quotes! Make sure that you always use a set of “s (double quotes). If you miss one, you get an error. Also make sure that the parentheses and curly braces are included in pairs; left one first, right one second.

The reward

Enough waiting! Run the WHORU program now. Type whoru or ./whoru at the command prompt and press the Enter key. The output looks like this: What is your name?

The program is now waiting for you to type your name. Go ahead: Type your name! Press Enter. 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. Reedit to fix any errors and then recompile. I/O is input/output, what computers do best. I/O, I/O, it’s off to code I go. . . . This program is an example that takes input and generates output. It doesn’t do anything with the input other than display it, but it does qual­ ify for I/O. The WHORU.C source code mixes two powerful C language functions to get input and provide output: printf() and scanf(). The rest of this chapter tells more about these common and useful functions in detail.

More on printf()

The printf() function is used in the C programming language to display information on the screen. It’s the all-purpose “Hey, I want to tell the user something” display-text command. It’s the universal electric crayon for the C language’s scribbling muscles.

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 a must. It’s followed by parentheses, which contain a quoted string of text, text (see the example). It’s printf()’s

job to display that text on the screen. In the C language, printf()is a complete statement. A semicolon always fol­ lows the last parenthesis. (Okay, you may see an exception, but it’s not worth fussing over at this point in the game.) Although text is enclosed in double quotes, they aren’t part of the mes­ sage that printf() puts up on the screen. You have to follow special rules about the text you can display, all of which are covered in Chapter 24. The format shown in the preceding example is simplified. A more advanced format for printf() appears later in this chapter.

Printing funky text Ladies and gentlemen, I give you the following: Ta da!

I am a text string.

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

I am a text string.”

Now you have a string of text, but that’s still nothing unless the computer can manipulate it. For manipulation, you need to wrap up the string in the bunlike parentheses: (“Ta da!

I am a text string.”)

Furthermore, you need an engine — a function — to manipulate the string. Put printf on one side and a semicolon on the other: printf(“Ta da!

I am a text string.”);

And, you have a hot dog of a C command to display the simple collection of text, numbers, letters, and other characters on the screen. Neat and tidy.

Is this criminal or what? It’s still a text string, but it contains the double-quote characters. Can you make that text a string by adding even more double quotes? “He said, “Ta da! I am a text string.””

Now there are four double quotes in all. That means eight tick marks hovering over this string’s head. How can it morally cope with that? “”Damocles” if I know.”

The C compiler never punishes you for “testing” anything. 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. Errors are safe! So why not experiment? Please enter the following source code, DBLQUOTE.C. The resulting program is another “printf() displays something” example. But this time, what’s dis­ played contains a double quote. Can you do that? This source code is your experiment for the day: #include int main() { printf(“He said, “Ta da! I am a text string.””); return(0); }

Type the source code exactly as it appears, including the double quotes — four in all. (You notice right away that something is wrong if your editor color-codes quoted text. But work with me here.) Save the source code file to disk as DBLQUOTE.C. Compile and run the preceding program — if you can. Chances are that you encounter one of these errors instead: dblequote.c: In function ‘main’: dblequote.c:5: parse error before “Ta”

or dblequote.c: In function ‘main’: dblequote.c:6: syntax error before “Ta”

43

44

Part I: Introduction to C Programming The printf() function requires a text string enclosed in double quotes. Your compiler knows that. After the second double quote in the string was encoun­ tered (before the word Ta), the compiler expected something else — something other than “Ta.” Therefore, an error was generated. Figure 4-1 illustrates this in a cute way.

The error happened right here, Officer.

Figure 4-1: The C

compiler

detects

something

amiss in the

printf("He said, "Ta da! I am a text string."");

printf()

statement.

Obviously, there is a need to use the double-quote character in a string of text. The question is how to pass that character along to printf() without it ruin­ ing the rest of your day. The answer is to use an escape sequence. In the olden days, programmers would have simply gone without certain char­ acters. Rather than trip up a string with a double quote, they would have used two single quotes. Some ancient programmers who don’t know about escape sequences still use these tricks.

Escape from printf()!

Escape sequences are designed to liven up an otherwise dull action picture with a few hard-cutting, loud-music moments of derring-do. 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. In the C language, escape sequences always begin with the backslash charac­ ter (\). Locate this character on your keyboard now. It should be above the Enter key, though they often hide it elsewhere. The backslash character signals the printf() function that an escape sequence is looming. When printf() sees the backslash, it thinks, “Omigosh, an escape sequence must be coming up,” and it braces itself to accept an otherwise forbidden character.

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). Behold, the new and improved Line 5: printf(“He said, \”Ta da! I am a text string.\””);

Notice the \” escape sequences in the text string. You see two of them, pre­ fixing the two double quotes that appear in the string’s midsection. The two outside double quotes, the ones that really are bookmarks to the entire string, remain intact. Looks weird, but it doesn’t cause an error. (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.) Edit your DBLQUOTE.C source code file. Make the escape-sequence modifica­ tion to Line 5, as just shown. All you have to do is insert two backslash char­ acters before the rogue double quotes: \”. Save the changed source code file to disk, overwriting the original DBLQUOTE.C file with the newer version. Compile and run. This time, it works and displays the following output: He said, “Ta da! I am a text string.”

The \” escape sequence produces the double-quote character in the middle of a string. Another handy escape sequence you may have used in Chapter 1 is \n. That produces a “new line” in a string, just like pressing the Enter key. You cannot “type” the Enter key in a text string, so you must use the \n escape sequence. All escape sequences start with the backslash character. 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. An escape sequence can appear anywhere in a text string: beginning, middle, or end and as many times as you want to use them. Essentially, the \ thing is a shorthand notation for sticking forbidden characters into any string. Other escape sequences are listed in Chapter 24 (in Table 24-1).

45

46

Part I: Introduction to C Programming

The f means “formatted”

The function is called printf() for a reason. The f stands for formatted. The advantage of the printf function over other, similar display-this-or-that func­ tions in C is that the output can be formatted. Earlier in this chapter, I introduce the format for the basic printf function as printf(“text”);

But the real format — shhh! — is printf(“format_string”[,var[,...]]);

What appears in the double quotes is really a formatting string. It’s still text that appears in printf()’s output, but secretly inserted into the text are var­ ious conversion characters, or special “placeholders,” that tell the printf() function how to format its output and do other powerful stuff. After the format string comes a comma (still inside the parentheses) and then one or more items called arguments. The argument shown in the preceding example is var, which is short for variable. You can use printf() to display the content or value of one or more variables. You do this by using special conversion characters in format_string. Figure 4-2 illustrates this concept rather beautifully.

First variable uses first conversion character

printf("blah blah %s blah %i.\n", str, num); Figure 4-2: How printf()

solves arguments.

Second variable uses second conversion character

The [,...] doohickey means that you can have any number of var items specified in a single printf function (before the final paren). Each var item, however, must have a corresponding placeholder (or conversion character) in format_string. They must match up, or else you get an error when the program is compiled.

Chapter 4: C What I/O

A bit of justification

To demonstrate how printf() can format text, as well as use those handy conversion characters and var things I scared you with in the preceding sec­ tion, how about a sample program? For your consideration is the following source code, which I have named JUSTIFY.C. Marvel at it: #include int main() { printf(“%15s”,”right\n”); printf(“%-15s”,”left\n”); return(0); }

What JUSTIFY.C does is to display two strings: right is right-justified, and left is left-justified. This makes more sense when you see the program’s output rather than just look at the source code. Enter this source code into your text editor. In the first printf statement, the first string is %15s (percent sign, 15, little s). That’s followed by a comma and then right, followed by the newline escape sequence, \n (backslash, little n). The second printf statement is nearly the same thing, though with a minus sign before the 15 and the string left rather than right. This program contains more C doodads than any other program introduced in the first three chapters in this book. Be careful with what you type! When you’re certain that you have it right, save the file to disk as JUSTIFY.C. Compile JUSTIFY.C. Fix any errors if you need to. Then run the program. Your output should look something like this: right left

The word right is right-justified 15 spaces over; left is left-justified. This arrangement was dictated by the %15s formatting command in printf(). The %15s part of the formatting string didn’t print at all. Instead, it controlled how the other string’s contents appeared on the screen. That’s the formatting power of printf() at work.

47

48

Part I: Introduction to C Programming

Maybe a little more help in understanding conversion characters To drive home how printf() uses its format­ ting string and arguments, bring up the source code for the GOODBYE.C program into your text editor. Change Line 5 to read: printf(“%s”,”Goodbye, cruel world!\n”); printf() has been modified to contain a for­

matting string and an argument. The formatting string is %s, which is the string (for s) placeholder. The argument is a string of text: “Goodbye, cruel world\!n”. Save the source code under a new filename, BYE.C. Compile and run. The output is the same

as the original; you have merely used the %s in the printf() function to “format” the output. 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. It has three string place­ holders, %s, and three strings in double quotes (with commas between them). Save. Compile. Run. The output should be the same. (If you get a compiling error, you probably have put a comma inside the double quotes, rather than between them.)

The JUSTIFY.C program shows you only a hint of what the printf() function can do. printf() can also format numbers in a remarkable number of ways, which is a little overwhelming to present right now in this chapter. 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. The percent character holds special meaning to printf(). It identifies a conversion character — what I call a “placeholder” — that tells printf how to format its output. The conversion character s means string: %s. Any numbers between the % and the s are used to set the width of the text string displayed. So, %15s means to display a string of text using 15 char­ acters. A minus sign before the 15 means to left-justify the string’s output. Doesn’t “left-justify” sound like a word processing term? Yup! It’s formatting! printf() doesn’t truncate or shorten strings longer than the width specified in the %s placeholder.

Chapter 4: C What I/O All this conversion-character stuff can get complex. Rest assured that seldom does anyone memorize it. Often, advanced programmers have to consult their C language references and run some tests to see which for­ matting command does what. Most of the time, you aren’t bothered with this stuff, so don’t panic.

scanf Is Pronounced “Scan-Eff”

Output without input is like Desi without Lucy, yang without yin, Caesar salad without the garlic. It means that the seven dwarves would be singing “Oh, Oh, Oh” rather than “I/O, I/O.” Besides — and this may be the most horrid aspect of all — without input, the computer just sits there and talks at you. That’s just awful. C has numerous tools for making the computer listen to you. A number of commands read input from the keyboard, from commands that scan for indi­ vidual characters to the vaunted scanf() function, which is used to snatch a string of text from the keyboard and save it in the cuddly, warm paws of a string variable. scanf() is a function like printf(). Its purpose is to read text from the keyboard. Like the f in printf(), the f in scanf() means formatted. You can use scanf() to read a specifically formatted bit of text from the keyboard. In this chapter, however, you just use scanf() to read a line of text, noth­ ing fancy.

Putting scanf together

To make scanf() work, you need two things. First, you need a storage place to hold the text you enter. Second, you need the scanf function itself. The storage place is called a string variable. String means a string of characters — text. Variable means that the string isn’t set — it can be what­ ever the user types. A string variable is a storage place for text in your pro­ grams. (Variables are discussed at length in Chapter 8.) The second thing you need is scanf() itself. 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.

49

50

Part I: Introduction to C Programming An example of using scanf() reads in someone’s first name. 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. And, just like the safe, the variable is “empty” when you create it; it doesn’t contain anything until you put something there. 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). firstname is the name of the storage location. When the source code refers to the variable, it uses this name, firstname. [20] defines the size of the string as being able to hold as many as 20

characters. All told, you have set aside space to hold 20 characters and named that space — that variable — firstname. The semicolon ends the C language statement. 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. Something like the following line would work: scanf(“%s”,&firstname);

Here’s how this statement works: scanf() is the function to read information from the keyboard. %s is the string placeholder; scanf() is looking for plain old text input

from the keyboard. Pressing the Enter key ends input. The text input is stored in the string variable named firstname. The ampersand is required here to help scanf() find the location of the string variable in memory. The semicolon ends the C language statement. Between the variable and scanf(), text is read from the keyboard and stored in the computer’s memory for later use. The next section coughs up an example.

Chapter 4: C What I/O If you’re writing a C program that requires input, you must create a place to store it. For text input, that place is a string variable, which you create by using the char keyword. Variables are officially introduced in Chapter 8 in this book. For now, con­ sider the string variable that scanf() uses as merely a storage chamber for text you type. The formatting codes used by scanf() are identical to those used by printf(). In real life, you use them mostly with printf() because there are better ways to read the keyboard than to use scanf(). Refer to Table 24-2 in Chapter 24 for a list of the formatting percent-sign place­ holder codes. Forgetting to stick the & in front of scanf()’s variable is a common mis­ take. Not doing so leads to some wonderful null pointer assignment errors that you may relish in the years to come. As a weird quirk, however, the ampersand is optional when you’re dealing with string variables. Go figure.

The miracle of scanf()

Consider the following pointless program, COLOR.C, which uses two string variables, name and color. It asks for your name and then your favorite color. The final printf() statement then displays what you enter. #include int main() { char name[20]; char color[20]; printf(“What is your name?”); scanf(“%s”,name); printf(“What is your favorite color?”); scanf(“%s”,color); printf(“%s’s favorite color is %s\n”,name,color); return(0); }

Enter this source code into your editor. Save this file to disk as COLOR.C. Compile. If you get any errors, double-check your source code and reedit the file. A common mistake: forgetting that there are two commas in the final printf() statement.

51

52

Part I: Introduction to C Programming Run the program! The output looks something like this: What is your name?dan What is your favorite color?brown dan’s favorite color is brown

In Windows XP, you have to run the command by using the following line: .\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.

Experimentation time!

Which is more important: the order of the %s doodads or the order of the variables — the arguments — in a printf statement? Give up? I’m not going to tell you the answer. You have to figure it out for yourself. Make the following modification to Line 12 in the COLOR.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. Save this change to disk and recompile. The program still runs, but the output is different because you changed the variable order. You may see something like this: brown’s favorite color is Dan.

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. The %s thingies? They’re just fill-in-the-blanks. How about making this change: printf(“%s’s favorite color is %s\n”,name,name);

This modification uses the name variable twice — perfectly allowable. All printf() needs are two string variables to match the two %s signs in its for­ matting string. Save this change and recompile. Run the program and exam­ ine the output: Dan’s favorite color is Dan

Chapter 4: C What I/O Okay, Lois — have you been drinking again? Make that mistake on an IRS form and you may spend years playing golf with former stockbrokers and congressmen. (Better learn to order your variables now.) Finally, make the following modification: printf(“%s’s favorite color is %s\n”,name,”blue”);

Rather than the color variable, a string constant is used. A string constant is simply a string enclosed in quotes. It doesn’t change, unlike a variable, which can hold anything. (It isn’t variable!) Save the change to disk and recompile your efforts. The program still works, though no matter which color you enter, the computer always insists that it’s “blue.” The string constant “blue” works because printf()’s %s placeholder looks for a string of text. It doesn’t matter whether the string is a variable or a “real” text string sitting there in double quotes. (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. I mean, ladies and gentlemen, where is the I/O?) The %s placeholder in a printf() function looks for a corresponding string variable and plugs it in to the text that is displayed. You need one string variable in the printf() function for each %s that appears in printf()’s formatting string. If the variable is missing, a syntax boo-boo is generated by the compiler. In addition to string variables, you can use string constants, often called literal strings. That’s kind of dumb, though, because there’s no point in wasting time with %s if you already know what you’re going to display. (I have to demonstrate it here, however, or else I have to go to C Teacher’s Prison in Connecticut.) Make sure that you get the order of your variables correct. This advice is especially important when you use both numeric and string variables in printf. The percent sign (%) is a holy character. Om! If you want a percent sign (%) to appear in printf’s output, use two of them: %%.

53

54

Part I: Introduction to C Programming

Chapter 5

To C or Not to C In This Chapter Inserting notes for yourself Using fancy commenting techniques Borrowing C++ comments Disabling code with comments Avoiding nested comments

A

n important part of programming is remembering what the heck it is you’re doing. 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. Instead, the thing you have to remember is what you are attempting to make a program do at a specific spot. You do that by inserting a comment in your source code.

Comments aren’t really necessary for the small programs you’re doing in this book. 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. To remind yourself of what you’re doing, you should stick a comment in the source code, explaining your approach. 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.

Adding Comments

Comments in a C program have a starting point and an ending point. 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. /* This is how a comment looks in the C language */

56

Part I: Introduction to C Programming This line is a fine example of a comment. 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: /*. The end of the comment is marked by the asterisk and the slash: */. Yup, they’re different. The comment is not a C language statement. You do not need a semi­

colon after the */.

A big, hairy program with comments

The following source code is MADLIB1.C. It uses the printf() and scanf() functions described in Chapter 4 to create a short yet interesting story: /*

MADLIB1.C Source Code

Written by (your name here)

*/

#include int main() {

char adjective[20];

char food[20];

char chore[20];

char furniture[20];

/* Get the words to use in the madlib */ printf(“Enter an adjective:”); /* prompt */

scanf(“%s”,&adjective); /* input */

printf(“Enter a food:”);

scanf(“%s”,&food);

printf(“Enter a household chore (past tense):”);

scanf(“%s”,&chore);

printf(“Enter an item of furniture:”);

scanf(“%s”,&furniture);

/* Display the output */

Chapter 5: To C or Not to C printf(“\n\nDon’t touch that %s %s!\n”,adjective,food); printf(“I just %s the %s!\n”,chore,furniture); return(0); }

Type the source code exactly as written. The only thing new should be the comments. Each one begins with /* and ends with */. Make sure that you get those right: A slash-asterisk begins the comment, and an asterisk-slash ends it. (If you’re using a color-coded editor, you see the comments all coded in the same color.) Save the file to disk and name it MADLIB1.C. Compile. Run. 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. Everything here, you have seen already: char to create string variables, printf() to display text and string variables, and scanf() to read the keyboard. Yawn. MADLIB1.C uses these four string variables: adjective, food, chore, and furniture. All four are created by the char keyword, and 20 characters of storage are set aside for each one. Each of the string variables is filled by scanf() with your keyboard input. Each of the final printf() functions contains two %s placeholders. Two string variables in each function supply the text for the %s placeholders. The second-to-last printf() function begins with two newline characters, \n \n. These characters separate the input section, where you enter the bits of text, from the program’s output. Yes, newlines can appear any­ where in a string, not just at the end. MADLIB1.C has five comments. Make sure that you can find each one. Notice that they’re not all the same, yet each one begins with /* and ends with */.

57

58

Part I: Introduction to C Programming

Why are comments necessary?

Comments aren’t necessary for the C compiler. It ignores them. Instead, com­ ments are for you, the programmer. They offer bits of advice, suggestions for what you’re trying to do, or hints on how the program works. You can put any­ thing in the comments, though the more useful the information, the better it helps you later on. Most C programs begin with a few lines of comments. All my C programs start with information such as the following: /* COOKIES.C Dan Gookin, 1/20/05 @ 2:45 a.m. Scan Internet cookie files for expired dates and delete. */

These lines tell me what the program is about and when I started working on it. In the source code itself, you can use comments as notes to yourself, such as /* Find out why this doesn’t work */

or this: save=itemv;

/* Save old value here */

or even reminders to yourself in the future: /* Someday you will write the code here that makes the computer remember what it did last time this program ran. */

The point is that comments are notes for yourself. If you were studying C pro­ gramming in school, you would write the comments to satiate the fixations of your professor. If you work on a large programming project, the comments placate your team leader. For programs you write, the comments are for you.

Comment Styles of the Nerdy and Not-Quite-Yet-Nerdy The MADLIB1.C program contains five comments and uses three different com­ menting styles. Though you can comment your programs in many more ways, these are the most common:

Chapter 5: To C or Not to C /* MADLIB1.C Source Code Written by Mike Rowsoft */

Ever popular is the multiline approach, as just shown. The first line starts the comment with the /* all by itself. Lines following it are all comments, remarks, or such and are ignored by the compiler. The final line ends the comment with */ all by itself. Remember that final /*; otherwise, the C compiler thinks that your whole program is just one big, long comment (possible, but not recommended). /* 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. The comment begins with /* and ends with */ all on the same line. It’s 100 percent okey-dokey, and, because it’s not a statement, you don’t need a semicolon. Finally, you can add the “end of line” comment: printf(“Enter an adjective:”);

/* prompt */

After the preceding printf statement plus a few taps of the Tab key, the /* starts a comment, and */ ends it on the same line.

Bizarr-o comments

During my travels, I have seen many attempts to make comments in C programs look interesting. Here’s an example: /***************************************** ** Commander Zero’s Excellent Program ** ******************************************/

This comment works. It contains lots of asterisks, but they’re all still stuck between /* and */, making it a viable comment. I have used this before in my programs: /* * This is a long-winded introduction to an * obscure program written by someone at a * university who’s really big on himself and * thinks no mere mortal can learn C -- and who * has written three “C” books to prove it. */

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. Another example I often use is this: /*****************************************/

That line of asterisks doesn’t say anything, yet it helps to break up different sections in a program. For example, I may put a line of asterisks between dif­ ferent functions so that I can easily find them. The bottom line: No matter what you put between them, a comment must start with /* and end with */.

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. I mention it simply because the C++ comment style can be useful, and it’s permitted if you want to borrow it. In C++, comments can start with a double slash, //. That indicates that the rest of the text on the line is a comment. 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.C program still keep the comments intact. 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.

Chapter 5: To C or Not to C

Using Comments to Disable

Comments are ignored by the compiler. No matter what lies between the /* and the */, it’s skipped over. Even vital, lifesaving information, mass sums of cash, or the key to eternal youth — all these are ignored if they’re nestled in a C language comment. Modify the MADLIB1.C source code, changing the last part of the program to read: /* Display the output */ /* printf(“\n\nDon’t touch that %s %s!\n”,adjective,food); printf(“I just %s the %s!\n”,chore,furniture); */

To make the modification, follow these cinchy steps: 1. Insert a line with /* on it before the first printf() function in this example. 2. Insert a line with */ on it after the second printf() function. With the last two printf() statements disabled, save the file to disk and recompile it. It runs as before, but the resulting “mad lib” isn’t displayed. The reason is that the final two printf() functions are “commented out.” You can use comments to disable certain parts of your program. If some­ thing isn’t working correctly, for example, you can “comment it out.” You may also want to include a note to yourself, explaining why that section is commented out. Sometimes you may notice that something which should be working isn’t working. The reason is that you may have accidentally commented it out. Always check your /* and */ comment bookends to make sure that they match up the way you want them to. By using an editor with color-coded text, you can easily spot missing */ characters to end a comment. If you notice that a greater chunk of your source code is colored as a comment, a misplaced */ is probably to blame.

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. To wit, I present the following C program fragment: if(all_else_fails) { display_error(erno); walk_away(); } else get_mad();

/* erno is already set */

Don’t worry about understanding this example; it all comes clear to you later in this book. However, notice that the display_error function has a comment after it: erno is already set. But suppose that, in your advanced under­ standing of C that is yet to come, you want to change the gist of this part of the program so that only the get_mad() function is executed. 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 /*. But it ends on the line with the display_error() function. Because that line ends with */ — the comment bookend — that’s the end of the “comment.” The C compiler then starts again with the walk_away function and generates a parse error on the rogue curly brace floating in space. The second comment bookend (just above the get_mad() function) also produces an error. Two errors! How heinous. This example shows a nested comment, or a comment within a comment. It just doesn’t work. Figure 5-1 illustrates how the C compiler interprets the nested comment. To avoid the nested-comment trap, you have to be careful when you’re dis­ abling portions of your C program. The solution in this case is to uncomment the erno is already set comment. Or, you can comment out each line individually, in which case that line would look like this:

Chapter 5: To C or Not to C /*

display_error(erno);

/* erno is already set */

This method works because the comment still ends with */. The extra /* inside the comment is safely ignored. Yeah, nested comments are nasty, but nothing you need to worry about at this point in the game. Note that the C++ style of comments, //, doesn’t have a nesting problem.

he printf() and scanf() functions aren’t the only way you can display information or read text from the keyboard — that old I/O. No, the C lan­ guage is full of I/O tricks, and when you find out how limited and lame printf() and scanf() are, you will probably create your own functions that read the keyboard and display information just the way you like. Until then, you’re stuck with what C offers. This chapter introduces the simple gets() and puts() functions. gets() reads a string of text from the keyboard, and puts() displays a string of text on the screen.

The More I Want, the More I gets()

Compared to scanf(), the gets() function is nice and simple. Both do the same thing: They read characters from the keyboard and save them in a vari­ able. gets() reads in only text, however. scanf() can read in numeric values and strings and in a number of combinations. That makes it valuable, but for reading in text, clunky.

66

Part I: Introduction to C Programming Like scanf() reading in text, gets() requires a char variable to store what’s entered. It reads everything typed at the keyboard until the Enter key is pressed. Here’s the format: gets(var); gets(), like all functions, is followed by a set of parentheses. Because gets()

is a complete statement, it always ends in a semicolon. Inside the parentheses is var, the name of the string variable text in which it is stored.

Another completely rude program example

The following is the INSULT1.C program. This program is almost identical to the WHORU.C program, introduced in Chapter 4, except that gets() is used rather than scanf(). #include int main() { char jerk[20]; printf(“Name some jerk you know:”); gets(jerk); printf(“Yeah, I think %s is a jerk, too.\n”,jerk); return(0); }

Enter this source code into your editor. Save the file to disk and name it INSULT1.C. Compile the program. Reedit the text if you find any errors. Remember your semicolons and watch how the double quotes are used in the printf() functions. Run the resulting program. The output looks something like this: Name some jerk you know:Bill Yeah, I think Bill is a jerk, too.

gets() reads a variable just like scanf() does. Yet no matter what reads it, the printf() statement can display it. gets(var) is the same as scanf(“%s”,var). If you get a warning error when compiling, see the next section.

Chapter 6: C More I/O with gets() and puts() You can pronounce gets() as “get-string” in your head. “Get a string of text from the keyboard.” However, it probably stands for “Get stdin,” which means “Get from standard input.” “Get string” works for me, though.

And now, the bad news about gets()

The latest news from the C language grapevine is not to use the gets() func­ tion, at least not in any serious, secure programs you plan on writing. That’s because gets() is not considered a safe, secure function to use. The reason for this warning — which may even appear when you compile a program using gets() — is that you can type more characters at the keyboard than were designed to fit inside the char variable associated with gets(). 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. For the duration of this book, don’t worry about using gets(). It’s okay here as a quick way to get input while finding out how to use C. But for “real” pro­ grams that you write, I recommend concocting your own keyboard-reading functions.

The Virtues of puts()

In a way, the puts() function is a simplified version of the printf() function. puts() displays a string of text, but without all printf()’s formatting magic. puts() is just a boneheaded “Yup, I display this on the screen” command. Here’s the format: puts(text); puts() is followed by a left paren, and then comes the text you want to dis­ play. That can either be a string variable name or a string of text in double quotes. That’s followed by a right paren. The puts() function is a complete C language statement, so it always ends with a semicolon.

The puts() function’s output always ends with a newline character, \n. It’s like puts() “presses Enter” after displaying the text. You cannot avoid this side effect, though sometimes it does come in handy.

67

68

Part I: Introduction to C Programming

Another silly command-prompt program

To see how puts() works, create the following program, STOP.C. Yeah, this program is really silly, but you’re just starting out, so bear with me: #include int main() { puts(“Unable to stop: Bad mood error.”); return(0); }

Save this source code to disk as STOP.C. Compile it, link it, run it. This program produces the following output when you type stop or ./stop at the command prompt: Unable to stop: Bad mood error.

Ha, ha. puts() is not pronounced “putz.” Like printf(), puts() slaps a string of text up on the screen. The text is hugged by double quotes and is nestled between two parentheses. Like printf(), puts() understands escape sequences. For example, you can use \” if you want to display a string with a double quote in it. You don’t have to put a \n at the end of a puts() text string. puts() always displays the newline character at the end of its output. If you want puts() not to display the newline character, you must use printf() instead.

puts() and gets() in action

The following program is a subtle modification to INSULT1.C. This time, the first printf() is replaced with a puts() statement: #include int main()

{

char jerk[20];

Chapter 6: C More I/O with gets() and puts() puts(“Name some jerk you know:”); gets(jerk); printf(“Yeah, I think %s is a jerk, too.”,jerk); return(0); }

Load the source code for INSULT1.C into your editor. Change Line 7 so that it reads as just shown; the printf is changed to puts. Use your editor’s Save As command to give this modified source code a new name on disk: INSULT2.C. Save. Compile. Run. Name some jerk you know: Rebecca Yeah, I think Rebecca is a jerk, too.

Note that the first string displayed (by puts()) has that newline appear after­ ward. That’s why input takes place on the next line. But considering how many command-line or text-based programs do that, it’s really no big deal. Other­ wise, the program runs the same as INSULT1. But you’re not done yet; con­ tinue reading with the next section.

More insults

The following source code is another modification to the INSULT series of pro­ grams. This time, you replace the final printf() with a puts() statement. Here’s how it looks: #include int main() { char jerk[20]; puts(“Name some jerk you know:”); gets(jerk); puts(“Yeah, I think %s is a jerk, too.”,jerk); return(0); }

Load the source code for INSULT2.C into your editor. Make the changes just noted, basically replacing the printf in Line 9 with puts. Otherwise, the rest of the code is the same. Save the new source code to disk as INSULT3.C. Compile and run.

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. According to what the compiler knows, you need only one or the other, not both. Oops. puts() is just not a simpler printf(). 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.

Ack! Who is this %s person who is such a jerk? Who knows! Remember that puts() isn’t printf(), and it does not process variables the same way. To puts(), the %s in a string is just %s — characters — nothing special.

puts() can print variables

puts() can display a string variable, but only on a line by itself. Why a line by itself? Because no matter what, puts() always tacks on that pesky newline character. You cannot blend a variable into another string of text by using the puts() function.

Consider the following source code, the last in the INSULT line of programs: #include int main() { char jerk[20]; puts(“Name some jerk you know:”); gets(jerk); puts(“Yeah, I think”); puts(jerk); puts(“is a jerk, too.”); return(0); }

Chapter 6: C More I/O with gets() and puts() Feel free to make the preceding modifications to your INSULT3.C program in your editor. Save the changes to disk as INSULT4.C. Compile. Run. Name some jerk you know: David Yeah, I think David is a jerk, too.

The output looks funky, like one of those “you may be the first person on your block” sweepstakes junk mailers. But the program works the way it was intended. Rather than replace printf() with puts(), you have to rethink your program’s strategy. For one, puts() automatically sticks a newline on the end of a string it displays. No more strings ending in \n! Second, puts() can display only one string variable at a time, all by itself, on its own line. And, last, the next bit of code shows the program the way it should be written by using only puts() and gets(). You must first “declare” a string variable in your program by using the char keyword. Then you must stick something in the variable, which you can do by using the scanf() or gets function. Only then does dis­ playing the variable’s contents by using puts() make any sense. Do not use puts() with a nonstring variable. The output is weird. (See Chapter 8 for the lowdown on variables.)

When to use puts() When to use printf() Use puts() to display a single line of text — nothing fancy.

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

Use puts() to display the contents of a string variable on a line by itself.

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() to display the contents of a variable nestled in the middle of another string.

Use printf() when fancy formatted output is required.

71

72

Part I: Introduction to C Programming

Part II

Run and Scream from Variables and Math

P

In this part . . .

rogramming a computer involves more than just splattering text on a screen. In fact, when you ask most folks, they assume that programming is some branch of mathematics or engineering. After all, computers have their roots in the calculators and adding machines of years gone by. And, early computers were heavily involved with math, from computing missile trajectories to landing men on the moon. I have to admit: Programming a computer does involve math. That’s the subject of the next several chapters, along with an official introduction to the concept of a variable (also a math thing). Before you go running and screaming from the room, however, consider that it’s the computer that does the math. Unlike those sweaty days in the back of eighth-grade math class, with beady-eyed Mr. Perdomo glowering at you like a fat hawk eyeing a mouse, you merely have to jot down the problem. The computer solves it for you. Relax! Sit back and enjoy reading about how you can slav­ ishly make the computer do your math puzzles. And, if it gets the answer wrong, feel free to berate it until the com­ puter feels like it’s only about yay high.

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. Yes, computers have something to do with math. But it’s more of a passing fancy than the infatuation you’re now dreading. Unless you’re some hard-core type of engineer (the enginerd), math­ ematics plays only a casual role in your programs. You add, subtract, divide, multiply, and maybe do a few other things. Nothing gets beyond the skills of anyone who can handle a calculator. 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. In this chapter, I try to make it as enjoyable as possible for you.

The Ever-Changing Variable

A variable is a storage place. The C compiler creates the storage place and sets aside room for you to store strings of text or values — depending on the type of storage place you create. You do this by using a smattering of C lan­ guage keywords that you soon become intimate with. What’s in the storage place? Could be anything. That’s why it’s called a vari­ able. Its contents may depend on what’s typed at the keyboard, the result of some mathematical operation, a campaign promise, or a psychic prediction. The contents can change too — just like the psychic prediction or campaign promise.

76

Part II: Run and Scream from Variables and Math It’s by juggling these variables that work gets done in most programs. 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). The number of points PacMan racks up are stored in a variable. And, when you win the game, you enter your name, and that too is stored in a variable. The value of these items — PacMan’s location, your points, your name — are changing or can change, which is why they’re stored in variables. Variables are information-storage places in a program. They can con­ tain numbers, strings of text, and other items too complex to get into right now. The contents of a variable? It depends. Variables are defined as being able to store strings of text or numbers. Their contents depend on what happens when the program runs, what the user types, or the computer’s mood, for example. Variables can change. Where are variables stored? In your computer’s memory. This informa­ tion isn’t important right now; the computer makes room for them as long as you follow proper variable-creating procedures in your C programs.

Strings change

The following program is brought to you by the keyword char and by the printf() and gets() functions. In this program, a string variable, kitty, is created, and it’s used twice as the user decides what to name her cat. The changing contents of kitty show you the gist of what a variable is: #include int main() { char kitty[20]; printf(“What would you like to name your cat?”); gets(kitty); printf(“%s is a nice name. What else do you have in mind?”,kitty); gets(kitty); printf(“%s is nice, too.\n”,kitty); return(0); }

Enter the source code for KITTY.C into your text editor. Save the file to disk as KITTY.C.

Chapter 7: A + B = C Compile KITTY.C. If you get any errors, reedit your source code. Check for missing semicolons, misplaced commas, and so on. Then recompile. Running the program is covered in the next section. The char keyword is used to create the variable and set aside storage for it. Only by assigning text to the variable can its contents be read. It’s the gets() function that reads text from the keyboard and sticks it into the string variable.

Running the KITTY

After compiling the source code for KITTY.C in the preceding section, run the final program. The output looks something like this: What would you like to name your cat?Rufus Rufus is a nice name. What else do you have in mind?Fuzzball Fuzzball is nice, too.

The kitty variable is assigned one value by using the first gets() function. Then, it’s assigned a new value by the second gets() function. Though the same variable is used, its value changes. That is the idea behind variables. A single variable can be used many times in a program. It can be used over and over with the same value, or used over and over to store differ­ ent values. It’s the contents of the string variable that are displayed — not the vari­ able name. In the KITTY.C program, the variable is named kitty. That’s for your reference as a programmer. What’s stored in the variable is what’s important.

Welcome to the Cold World of Numeric Variables Just as strings of text are stored in string variables, numbers are stored in numeric variables. This allows you to work with values in your program and to do the ever-dreaded math.

77

78

Part II: Run and Scream from Variables and Math To create a numeric variable and set aside storage space for a number, a spe­ cial C language keyword is used. Unlike char, which creates all types of strings, different keywords are used to create variables for storing different types of numbers. It all depends on how big or how weird the number is.

Hello, integer

To keep things sane for now, I show you only one of the numeric variable types. It’s the simplest form of a number, the integer. Just say “IN-tuh-jur.” Integer. 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. An integer can have a value that ranges from 0 to 32,767. Negative numbers, from –32,768 up to 0 are also allowed. Any other values — larger or smaller, fractions, or values with a decimal point, such as 1.5 — are not integers. (The C language can deal with such numbers, but I don’t introduce those types of variables now.) To use an integer variable in a program, you have to set aside space for it. You do this with the int keyword at the beginning of the program. 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. It’s a complete statement in the C language, and it ends with a semicolon. Some compilers may define the range for an int to be much larger than –32,768 through 32,767. To be certain, check with your compiler’s docu­ mentation or help system. On older, 16-bit computers, an integer ranges in value from –32,768 through 32,767. On most modern computers, integer values range from –2,147,483,647 through 2,147,483,647. More information about naming a variable — and other C language trivia about variables — is offered in Chapter 8. For now, forgive me for the unofficial introduction.

Chapter 7: A + B = C Yes! You’re very observant. This type of int is the same one used to declare the main() function in every program you have written in this book — if you have been reading the chapters in order. Without getting too far ahead, you should now recognize that main() is known as an “integer function.” It also ties into the 0 value in the return statement, but I tell you more about that in a few chapters. 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. If, per­ chance, you ever program on a large, antique computer — doomed to ever-dwindling possibilities of employment, like those losers who pro­ gram them — you may discover that the range for integers on those computers is somewhat different. Yeah, this information is completely optional; no need cluttering your head with it. But they would whine if I didn’t put it in here.

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. As an example, the following program uses the variable age to keep track of someone’s age. 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). Think “whole numbers, not big.” 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. The program is METHUS1.C, from Methus, which was his nickname: #include int main() { int age; age=969; printf(“Methuselah was %d years old.\n”,age); return(0); }

Enter the text from METHUS1.C into your editor. Save the file to disk as METHUS1.C.

79

80

Part II: Run and Scream from Variables and Math Compile the program. If you get any errors, reedit the source code and make sure that everything matches the preceding listing. Recompile. Run the program and you see the following: Methuselah was 969 years old.

The variable age was assigned the value 969. Then, the printf() statement was used, along with the %d placeholder, to display that value in a string. The fifth line creates the age variable, used to store an integer value. The seventh line assigns the value 969 to the age variable by using the equal sign (=). The variable age comes first, and then the equal sign, and then the value (969) to be placed in the age variable. In the eighth line, the printf function is used to display the value of the age variable. In printf()’s formatting string, the %d conversion charac­ ter is used as a placeholder for an integer value. %d works for integers, just as %s is a placeholder for a string.

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 (=). The variable goes on the left, and then the equal sign, and then the “thing” that produces the value on the right. That’s the way it is, was, and shall be in the C language: var=value;

var is the name of the numeric variable. value is the value assigned to that variable. Read it as “The value of the variable var is equal to the value value.” (I know, too many values in that sentence. So shoot me.) What could value be? It can be a number, a mathematical equation, a C lan­ guage function that generates a value, or another variable, in which case var has that variable’s same value. Anything that pops out a value — an integer value, in this case — is acceptable. In METHUS1.C, the value for the variable age is assigned directly: age=969;

Lo, the value 969 is safely stuffed into the age variable.

Chapter 7: A + B = C The equal sign is used to assign a non-string value to a variable. The variable goes on the left side of the equal sign and gets its value from whatever’s on the right side. String variables cannot be defined in this way, by using an equal sign. 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. String variables can also be preset, but you cannot use an equal sign with them, like you can with numeric variables!

Entering numeric values from the keyboard Keep the METHUS1.C program warm in your editor’s oven for a few seconds. What does it really do? Nothing. Because the value 969 is already in the pro­ gram, there’s no surprise. The real fun with numbers comes when they’re entered from the keyboard. Who knows what wacky value the user may enter? (That’s another reason for a variable.) A small problem arises in reading a value from the keyboard: Only strings are read from the keyboard; the scanf() and gets() functions you’re familiar with have been used to read string variables. And, there’s most definitely a dif­ ference between the characters “969” and the number 969. One is a value, and the other is a string. (I leave it up to you to figure out which is which.) The object is to covertly transform the string “969” into a value — nay, an integer value — of 969. The secret command to do it is atoi, the A-to-I function.

The atoi() function

The atoi() (pronounced “A-to-I”) function converts numbers at the begin­ ning of a string into an integer value. The A comes from the acronym ASCII, which is a coding scheme that assigns secret code numbers to characters. So atoi means “convert an ASCII (text) string into an integer value.” That’s how you can read integers from the keyboard. Here’s the format: var=atoi(string);

var is the name of a numeric variable, an integer variable created by the int keyword. That’s followed by an equal sign, which is how you assign a value to a variable.

81

82

Part II: Run and Scream from Variables and Math

On the difference between numbers and strings, if you dare to care You have to know when a number in C is a value and when it’s a string. A numeric value is what you find lurking in a numeric variable. This book calls those things values, and not numbers. A value is 5 apples, 3.141 (for example), the national debt, and the number of pounds you can lose on celebrity diets featured in this week’s Star. Those are values. Numbers are what appear in strings of text. When you type 255, for example, you’re enter­ ing a string. Those are the characters 2, 5, and 5, as found on your keyboard. The string “255” is not a value. I call it a number. By using the

atoi() function in the C language, you can

translate it into a value, suitable for storage in a numeric variable. There are numbers and there are values. Which is which? It depends on how you’re going to use it. Obviously, if someone is entering a phone number, house number, or zip code, it’s probably a string. (My zip code is 94402, but that doesn’t mean that it’s the 94-thousandth-something post office in the United States.) If some­ one enters a dollar amount, percentage, size, or measurement — anything you work with mathematically — it’s probably a value.

The atoi() function follows the equal sign. Then comes the string to con­ vert, hugged by atoi()’s parentheses. The string can be a string variable or a string “constant” enclosed in double quotes. Most often, the string to convert is the name of a string variable, one created by the char keyword and read from the keyboard by using gets() or scanf() or some other keyboardreading function. The line ends in a semicolon because it’s a complete C language statement. The atoi function also requires a second number-sign thingy at the begin­ ning of your source code: #include

This line is usually placed below the traditional #include thing — both of them look the same, in fact, but it’s stdlib.h in the angle pinchers that’s required here. The line does not end with a semicolon. atoi is not pronounced “a toy.” It’s “A-to-I,” like what you see on the spine of Volume One of a 3-volume encyclopedia. Numbers are values; strings are composed of characters. If the string that atoi() converts does not begin with a number, or if the number is too large or too weird to be an integer, atoi spits back the value 0 (zero).

Chapter 7: A + B = C The purpose of #include is to tell the compiler about the atoi() function. Without that line, you may see some warning or “no prototype” errors, which typically ruin your programming day. STDLIB.H is the standard library header file, don’t you know. Other C language functions are available for converting strings into noninteger numbers. 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.

So how old is this Methuselah guy, anyway? The following program is METHUS2.C, a gradual, creeping improvement over METHUS1.C. In this version of the program, you read a string that the user types at the keyboard. That string — and it is a string, by the way — is then magically converted into a numeric value by the atoi() function. Then, that value is displayed by using the printf() function. A miracle is happening here, something that the ancients would be truly dazzled by, probably to the point of offering you food and tossing fragrant posies your way. #include #include int main() { int age; char years[8]; printf(“How old was Methuselah?”); gets(years); age=atoi(years); printf(“Methuselah was %d years old.\n”,age); return(0); }

Hunt and peck the METHUS2.C source code into your editor. You can edit the original METHUS1.C source code, but be careful to save it to disk under the new name, METHUS2.C. Compile the program. Repair any errors you may have encountered. Run the program. The output you see may look something like this: How old was Methuselah?26 Methuselah was 26 years old.

83

84

Part II: Run and Scream from Variables and Math

No, you don’t have to experiment with METHUS2.C, but I encourage you to try this Thank goodness this book isn’t Surgery For Dummies. Unlike that sober tome, this book allows you to freely fiddle, poke, pull, experi­ ment, and have fun. Trying that with a cadaver is okay, but in Chapter 14 of Surgery For Dummies, “Finding That Pesky Appendix on Your Nephew,” it’s frowned on. Run the METHUS2.C program again, and when the program asks you for Methuselah’s age, type the following value: 10000000000

That’s ten billion — a one with 10 zeroes and no commas. 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 reason is that you entered a value greater than an integer can hold. The value returned is the remainder of what you entered divided by the maximum size of an integer in your compiler.

Yes, Mr. M. could never be negative 64 years old, but the program accepts it. The reason is that integer values include negative numbers. Here’s one you need to try: 4.5

Is the oldest human really four-and-a-half? Probably at one time. Still, the program insists that he was only four. That’s because the point­ 5 part is a fraction. Integers don’t include frac­ tions, so all the atoi() function reads is the 4. Finally, the big experiment. Type the following as Methus’s age: old

Yes, he was old. But when you enter old into the program, it claims that he was only zero. The reason is that the atoi() function didn’t see a number in your response. Therefore, it gener­ ates a value of zero.

How about typing the following value: -64

In this example, the user typed 26 for the age. That was entered as a string, transformed by atoi() into an integer value and, finally, displayed by printf(). That’s how you can read in numbers from the keyboard and then fling them about in your program as numeric values. Other sections in this chapter, as well as in the rest of this book, continue to drive home this message. Okay, legend has it that the old man was 969 when he finally (and prob­ ably happily) entered into the hereafter. 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). If you forget the #include thing or you misspell it, a few errors may spew forth from your compiler. Normally, these errors are tame “warnings,” and the program works just the same. Regardless, get

Chapter 7: A + B = C in the habit of including the stdlib thing when you use the atoi() function. The age=atoi(years) function is how the string years is translated into a numeric value. The atoi() function examines the string and spits up a number. That number is then placed in the age variable as a numeric value. Why not just print the string years? Well, you can. By replacing age with years and %d with %s in the final printf() function, the program dis­ plays the same message. To wit: printf(“Methuselah was %s years old.\n”,years);

The output is the same. However, only with a numeric variable can you perform mathematical operations. Strings and math? Give up now and keep your sanity!

You and Mr. Wrinkles

Time to modify the old Methuselah program again. This time, you create the METHUS3.C source code, as shown next. As with METHUS2.C, only subtle modifications are made to the original program. Nothing new, though you’re building up to something later in this chapter. #include #include 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”,you); printf(“Methuselah was %d years old.\n”,methus); return(0); }

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

85

86

Part II: Run and Scream from Variables and Math Compile METHUS3.C. Fix any errors that sneak into the picture. Run the program. 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. Methuselah was 969 years old.

Of course, this data is merely regurgitated. The true power of the computer is that math can be done on the values — and it’s the computer that does the math, not you. Don’t sweat it! You’re not really 29. Yes, the years string variable is used twice. First, it reads in your age, and then the atoi() function converts it and saves the value in the you variable. Then, years is used again for input. This strategy works because the original value was saved in another variable — a cool trick. The METHUS3.C program has been divided into four sections. This is more of a visual organization than anything particular to the C program­ ming language. The idea is to write the program in paragraphs — or thoughts — similar to the way most people try to write English.

A Wee Bit o’ Math

Now is the time for all good programmers to do some math. No, wait! Please don’t leave. It’s cinchy stuff. The first real math explanation is several pages away. When you do math in the C programming language, it helps to know two things: First, know which symbols — or, to be technical, unique doodads — are used to add, subtract, multiply, and divide numbers. Second, you have to know what to do with the results. Of course, you never have to do the math. That’s what the computer is for.

Basic mathematical symbols

The basic mathematical symbols are probably familiar to you already if you have been around computers a while. 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. These are mathematical (or arithmetic — I never know which to use) operators. + Addition: The addition operator is the plus sign, +. This sign is so basic that I can’t really think of anything else you would use to add two numbers: var=value1+value2;

Here, the result of adding value1 to value2 is calculated by the computer and stored in the numeric variable var. – 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. * Multiplication: Here’s where we get weird. 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. / Division: For division, the slash, /, is used; the primary reason is that the ÷ symbol is not on your keyboard: var=value1/value2;

Here, the result of dividing value1 by value2 is calculated by the computer and 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. More properly, it’s the × symbol, not the character X (or even little x). It’s pro­ nounced “times,” as in “four times nine” for 4×9. In higher math, where it was harder for you to get an “easy A,” the dot was also used for mul­ tiplication: 4•9 for “four times nine.” I have even seen that expressed as 4(9) or (4)(9), though I fell right back asleep.

know when you mean X as in “ecks” and × as in “times.” So, the asterisk (*) was accepted as a substitute. (The keyboard has no dot • character either.) Using the * for multiplication takes some getting used to. The slash is kind of common — 3/$1 for “three for a dollar” or 33 cents each — so that’s not a problem. But the * takes some chanting and bead counting.

Why can’t computers use the X? Primarily because they’re stupid. The computer doesn’t

It just doesn’t work in the C language. The preceding line tells the C compiler to take the value of the var variable and put it into some numbers. 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.) More mathematical symbols, or operators, are used in C programming. This chapter introduces only the four most common symbols. Having trouble remembering the math operators? Look at your keyboard’s numeric keypad! The slash, asterisk, minus, and plus symbols are right there, cornering the number keys. 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 don’t always have to work with two values in your mathematical functions. You can work with a variable and a value, two variables, functions — lots of things. C is flexible, but at this stage it’s just impor­ tant to remember that * means “multiply.”

How much longer do you have to live to break the Methuselah record? The following METHUS4.C source code uses a bit of math to figure out how many more years you have to live before you can hold the unofficial title of the oldest human ever to live (or at least tie with him).

Chapter 7: A + B = C Before you do this, I want you to think about it. What are the advantages of being the oldest person ever to live? What else do we know about Methuselah? He died before the flood. He was a good man, well received by The Man Upstairs. But, what else? I mean, like, did he eat weird or some­ thing? Did he avoid the grape? The Bible offers no hints. #include #include 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.\n”,diff); return(0); }

The METHUS4.C program is eerily similar to METHUS3.C. It has only a few deviations, so you can edit the METHUS3.C source code and then save it to disk as METHUS4.C. Cross-check your work with the preceding source code listing, just to be sure. Compile the program. Fix any errors that may crop up. Then run the final product. Your output may look something like the following: How old are you?29 You are 940 years younger than Methuselah.

Try entering a different age to see how it compares with Methuselah’s. It does math! It does math! This program uses four — four! — variables: diff, methus, and you are all integer variables. years is a string variable. What happens if you enter a negative age — or an age greater than 969?

89

90

Part II: Run and Scream from Variables and Math To figure out how much longer you have to live to match Methuselah’s record, you subtract your age from his. 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. Your age, stored in the you numeric variable, is subtracted from Methuselah’s and stored in the diff numeric variable. The result then slides through the equal sign and into the diff numeric variable.

Bonus modification on the final Methuselah program! Methuselah works hard until he’s 65, and then he retires. Because he got his first job at 19, he has been contributing to Social Security. As soon as he hits 65, he starts drawing his money out. And out. And out. And out some more. How about writing a program that can do what no bureaucrat in Washington can do: Figure out how much money Methuselah is drawing from the system? (We leave the “whether he earned it all” question up to future generations because, of course, if you ask Methuselah himself, he says that he did.) #include #include int main() { int contributed; int received; contributed=65-19; received=969-65; printf(“Methuselah contributed to Social Security for %i years.\n”,contributed); printf(“Methuselah collected from Social Security for %i years.\n”,received); return(0); }

Type into your editor the source code for METHUS5.C — which I promise is the last of the Methuselah suite of programs. Double-check your typing and all that stuff. Your fine sense of logic wants you to type i before e in received, though the illogic of English dictates otherwise. Save the file as METHUS5.C.

Chapter 7: A + B = C Compile it! Check for any errors or small pieces of meat the compiler may choke on. Dislodge them (reedit the source code) and compile again if you need to. Run the program! Here’s a sample of the output: Methuselah contributed to Social Security for 46 years. Methuselah collected from Social Security for 904 years.

It seems fair to him. Line 10 calculates how long Methuselah has been receiving Social Security. If he died at 969 and began receiving checks at 65, the differ­ ence is the value you want. That’s stored in the received variable. Notice how the smaller value is subtracted from the larger? C works from left to right with math: 65 minus 19; 969 minus 65. Still, the math part of the equation must be on the right. The variable that holds the result is on the left. When math is used in a program with numbers rather than variables, the numbers are called constants. You can find more information on the subject of constants in Chapter 8.

The direct result Are variables necessary? Yes, when the value isn’t known. In the last few Methuselah programs, the values were known, for the most part. Only when you enter your own age is there truly a need for a variable. Otherwise, con­ stant values can be used. For example, the following program is another version of METHUS5. You don’t have to type this program, but look at the only two statements in the program. Gone are the variables and the statements that assigned them values, as well as the #include because atoi() isn’t being used: #include int main() { printf(“Methuselah contributed to Social Security for %d years.\n”,65-19); printf(“Methuselah collected from Social Security for %d years.\n”,969-65); return(0); }

91

92

Part II: Run and Scream from Variables and Math The %d in the first printf() function looks for an integer value to “fill in the blank.” 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 printf() statement plugs the value 46 into the %d’s placeholder. The same holds true for the second printf() function. You can do the same thing without the math. 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”,46); printf(“Methuselah collected from Social Security for %d years.\n”,904);

Again, the result is the same. The %d looks for an integer value, finds it, and plugs it in to the displayed string. It doesn’t matter to printf() whether the value is a constant, a mathematical equation, or a variable. It must, however, be an integer value.

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. Programming just can’t get done without them. You may have just dabbled with variables, but not been formally introduced. In this chapter, you’re formally introduced!

Cussing, Discussing, and Declaring Variables Along comes Valerie Variable. . . . Valerie is a numeric variable. She loves to hold numbers — any number — it doesn’t matter. Whenever she sees an equal sign, she takes to a value and holds it tight. But see another equal sign, and she takes on a new value. In that way, Valerie is a little flaky. You could say that Valerie’s values vary, which is why she’s a variable.

94

Part II: Run and Scream from Variables and Math Victor is a string variable. He contains bits of text — everything from one char­ acter to several of them in a row. As long as it’s a character, Victor doesn’t mind. But which character? Victor doesn’t care — because he’s a variable, he can hold anything. Yes, I have a point here. C has two main types of variables: numeric vari­ ables, which hold only numbers or values, and string variables, which hold text, from one to several characters long. The C language has several different types of numeric variables, depend­ ing on the size and precision of the number. The details are in Chapter 9. Before you use a variable, it must be declared. This is — oh, just read the next section.

“Why must I declare a variable?”

You’re required to announce your variables to the C compiler before you use them. You announce them by providing a list of variables near the top of the source code. That way, the compiler knows what the variables are called and what flavor of variables they are (what values they can contain). Officially, this process is known as declaring your variables. 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. Declaring variables at the beginning of the program tells the compiler several things. 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. Second, the declarations tell the compiler which type of variable is being used. The compiler knows that integer values fit into the count variable, for example. Third, the compiler knows how much storage space to set aside for the vari­ ables. This can’t be done “on the fly,” as the program runs. The space must be set aside as the program is created by the compiler.

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. Cluster them all up right there. Obviously, you don’t know all the variables a program requires before you write it. (Though they teach otherwise at the universities, such mental overhead isn’t required by you and me.) If you need a new vari­ able, use your editor to declare it in the program. Rogue variables — those undeclared — generate syntax or linker errors (depending on how they’re used). If you don’t declare a variable, your program doesn’t compile. A suitable complaint message is issued by the proper authorities. Most C programmers put a blank line between the variable declarations and the rest of the program. There’s nothing wrong with commenting a variable to describe what it contains. For example: int count; /* busy signals from tech support. */

However, cleverly named variables can avoid this situation: int busysignals;

Or, even better: int busy_signal_count;

Variable names verboten and not What you can name your variables depends on your compiler. You have to follow a few rules, and you cannot use certain names for variables. When you break the rules, the compiler lets you know by flinging an error message your way. 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. Use variable names that mean something. Single-letter variables are just hunky-dory. But index is better than i, count is better than c, and name is better than n. Short, descriptive variable names are best. Variables are typically in lowercase. (All of C is lowercase, for the most part.) They can contain letters and numbers. Uppercase letters can be used in your variables, but most compilers tend to ignore the differences between upper- and lowercase letters. (You can tell the compiler to be case-sensitive by setting one of its options; refer to your compiler’s online help system for the details.)

95

96

Part II: Run and Scream from Variables and Math You shouldn’t begin a variable name with a number. It can contain num­ bers, but you begin it with a letter. 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. C lords use the underline, or underscore, character in their variable names: first_name and zip_code, for example. This technique is fine, though it’s not recommended to begin a variable name with an under­ line. Avoid naming your variables the same as C language keywords or func­ tions. Don’t name your integer variable int, for example, or your string variable char. This may not generate an error with your compiler, but it makes your source code confusing. (Refer to Table 3-1, in Chapter 3, for a list of the C language keywords.) Also avoid using the single letters l (lowercase L) and o (lowercase O) to name variables. Little L looks too much like a 1 (one), and O looks too much like a 0 (zero). Don’t give similar names to your variables. For example, the compiler may assume that forgiveme and forgivemenot are the same variable. If so, an ugly situation can occur. Buried somewhere in the cryptic help files that came with your compiler are the official rules for naming variables. These rules are unique to each compiler, which is why I’m not mentioning them all here. After all, I’m not paid by the hour. And it’s not part of my contract.

Presetting variable values

Suppose that this guy named Methuselah is 969 years old. I understand that this may be a new, bold concept to grasp, but work with me here. 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. That requires two steps. 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. Then comes the assignment, when 969 is put into the variable methus: methus=969;

Chapter 8: Charting Unknown Cs with Variables In C, you can combine both steps into one. For example: int methus=969;

This statement creates the integer variable methus and assigns it the value 969 — all at once. It’s your first peek at C language shortcut. (C is full of short­ cuts and alternatives — enough to make you kooky.) You can do the same thing with string variables — but it’s a little weird. Normally, string variables are created and given a size. For example: char prompt[22];

Here, a character string variable, prompt, is created and given room for 22 characters. Then you use gets() or scanf() to stick text into that variable. (You don’t use an equal sign!) When you create the variable and assign it a string, however, it’s given this format: char prompt[] = “So how fat are you, anyway?”

This command creates a string variable, prompt. That string variable already contains the text “So how fat are you, anyway?” Notice that you see no number in the brackets. The reason is that the compiler is smart enough to figure out how long the string is and use that value automatically. No guesswork — what joy! Numeric variables can be assigned a value when they’re declared. Just follow the variable name with an equal sign and its value. Remember to end the line with a semicolon. You can even assign the variable a value concocted by using math. 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. (Remember that * is used for multi­ plication in C.) Even though a variable may be assigned a value, that value can still change. If you create the integer variable methus and assign it the value 969, there’s nothing wrong with changing that value later in the program. After all, a variable is still a variable. Here’s a trick that’s also possible, but not necessary, to remember: int start = begin = first = count = 0;

97

98

Part II: Run and Scream from Variables and Math This statement declares four integer variables: start, begin, first, and count. Each of them is set equal to 0. start is equal to begin, which is equal to first, which is equal to count, which is equal to 0. You probably see this type of declaration used more often than you end up using it yourself.

Type this source code into your editor. Double-check everything. Save the program as ICKYGU.C. Compile the program. Repair any unexpected errors — as well as those you may have been expecting — and recompile if need be. Run the final program. You see something like the following example displayed: Today special - Slimy Orange Stuff “Icky Woka Gu” You want 1 pint. That be $1.450000, please.

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. But the 1.45 value was printed with four extra zeroes. Why? Because you didn’t tell the compiler not to. That’s just the way the %f, or floating-point conver­ sion character, displays numbers.

Chapter 8: Charting Unknown Cs with Variables To have the output make more dollars and sense, edit Line 11 and change the %f placeholder to read %.2f: printf(“That be $%.2f, please.\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. Here, you’re telling printf() to format the floating-point number to only two places after the decimal point. Save the change to disk. Recompile and run. The output is more appealing: Today special - Slimy Orange Stuff “Icky Woka Gu” You want 1 pint. That be $1.45, please.

This program contains three types of variables: a string, menuitem; an integer value, pints; and a floating-point value, price. The price is a floating-point value because it contains a decimal part. It’s another type of numeric variable. Unlike an integer, floating-point values can contain a decimal part. The “floating point” is that dot in the middle of the number — 1.45 — which is technically incorrect, but it’s the way I remember it. Table 24-2 in Chapter 24 contains a list of the printf() function’s place­ holders. There, you find that %f is used to display a floating-point number, such as the one that appears in ICKYGU.C. The final printf() statement is used to display the value of the floatingpoint price variable: printf(“That be $%.2f, please.\n”,price);

To do that, you use the %f (f for float) placeholder. However, %f requires some extra formatting power to display the value as a monetary amount. To meet this end, you insert a “dot-2” between the % and the little f. That formats the output to only two decimal places. Rather than use %f, the formatting string uses %.2f.

Maybe you want to chance two pints?

You can easily twist ICKYGU.C into doing some math for you. Suppose that you want to figure out how much two pints of the orange stuff is. First, you change the pints variable in the sixth line to read int pints=2;

99

100

Part II: Run and Scream from Variables and Math That fills the pints variable with 2. Then you have to stick some math into the final printf() function, which calculates how much two pints of the sticky stuff would be. Make these alterations: printf(“That be $%.2f, please.\n”,pints*price);

The only true change is in the last part of the line. Before, you had only the price variable. Now, you have pints*price, which multiplies the value in price by the value in pints. Because price is a floating-point, or decimal, value, the result still is floating-point. That is the reason that the %f place­ holder is still used in the formatting string. Save these changes and recompile the program. You have to pay more, but — mmmm — your tummy will thank you.

Multiple declarations

C is full of abbreviations and shortcuts. That’s one reason that no two C pro­ grams look alike: Programmers always take advantage of the different ways of doing things. One such trick is to declare several variables in one statement. I know — this used to be illegal in parts of the South, but it’s now done above­ board everywhere in the Union. 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. Each is followed by a comma, with the final variable followed by a semicolon to end the statement. This shortcut is primarily a space-saving technique. It just takes up less screen space to declare all variables of one type on a single line than to have individ­ ual, itsy-bitsy int statements lining up at the beginning of a program. You can declare variables of only the same type in a multiple declaration. For example: int top,bottom,right,left; float national_debt,pi;

Chapter 8: Charting Unknown Cs with Variables The integer variables are declared on one line, and the floating-point (non­ integer) variables on another. Keep variables that are defined with a value on a line by themselves. To wit: int first=1; int the_rest;

Constants and Variables

In addition to the variable, the C language has something called a constant. It’s used like a variable, though its value never changes. Suppose that one day someone dupes you into writing a trigonometry pro­ gram. In this type of program, you have to use the dreaded value π (pi). That’s equal to 3.1415926 (and on and on). Because it never changes, you can create a constant named pi that is equal to that value. 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 variable can go there, though a string constant — a literal, quoted string — is used instead. A constant is used just like a variable, though its value never changes. A numeric constant is a number value, like π, that remains the same throughout your program. π is pronounced “pie.” It’s the Greek letter p. We pronounce the English letter p as “pee.” A string constant is a bit of text that never changes, though that’s really true of most text in a C language program. This chapter, therefore, con­ centrates primarily on numeric constants.

Dreaming up and defining constants

All this constant nonsense can seem silly. Then one day, you’re faced with a program like SPEED.C — except that the program is much longer — and you truly come to realize the value of a C language constant and the nifty #define directive you read about later in this chapter:

101

102

Part II: Run and Scream from Variables and Math #include int main() { printf(“Now, the speed limit here is %i.\n”,55); printf(“But I clocked you doin’ %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. Carefully type the preceding source

code. There’s nothing new or repulsive in it. Save the file to disk as SPEED.C.

Compile it! Fix it (if you have to)! Run it!

The output is pretty plain; something like this example is displayed:

Now, the speed limit here is 55. But I clocked you doin’ 70. Didn’t you see that 55 MPH sign?

Eh? No big deal. 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. Better still, what if the program were 800 lines long and you had to do that? Not only that, but what if you had to change several other instances in which constants were used, and using your editor to hunt down each one and replace it properly would take months or years? Fortunately, the C language has a handy way around this dilemma. You can easily argue that this isn’t a problem. After all, most editors have a search-and-replace command. Unfortunately, searching and replacing numbers in a computer program is a dangerous thing to do! Suppose that the number is 1. Searching and replacing it would change other values as well: 100, 512, 3.141 — all those would be goofed up by a search-andreplace. For all you Mensa people out there, it’s true that the nature of the pro­ gram changes if the speed limit is lowered to 45. After all, was the scofflaw doing 70 or 60? To me, it doesn’t matter. If you’re wasting your excess IQ points on the problem, you can remedy it on your own.

The handy shortcut

The idea in this section is to come up with a handy shortcut for using number constants in C. I give you two solutions.

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. To change the speed, you have to make only one edit: int speed=45;

Although this line works, it’s silly because a variable is designed to hold a value that changes. 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. No, the true solution is to define the constant value as a symbolic con­ stant. It’s really cinchy, as the updated SPEED.C program shows: #include #define SPEED 55 int main() { printf(“Now, the speed limit here is %i.\n”,SPEED); printf(“But I clocked you doin’ %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 (#). This one, #define, sets up a numeric con­ stant that can be used throughout the program: #define SPEED 55

As with the #include thing, a semicolon doesn’t end the line. In fact, two big boo-boos with #define are using an equal sign and ending the line with a semicolon. The compiler will surely hurl error-message chunks your way if you do that. The shortcut word SPEED is then used in the program’s three printf() statements to represent the value 55. There, it appears just like a number or variable in the printf statement. Secretly, what happens is that the compiler sees the #define thing and all by itself does a search-and-replace. When the program is glued together, the value 55 is stuck into the printf() statements. The advantage is that you can easily update the constant values by simply editing the #define directive.

103

104

Part II: Run and Scream from Variables and Math Carefully edit your SPEED.C source code so that it matches what you see listed here. Save the file to disk again and then recompile. 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. Again, the key is that it takes only one, quick edit to change the speed limit. 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. This change saves some time for the SPEED.C program — but it saves you even more time for longer, more complex programs that also use constant values. Symbolic constant is C technospeak for a constant value created by the #define directive.

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. Here’s the format: #define SHORTCUT value SHORTCUT is the name of the constant you’re defining. It’s traditional to name it like a variable and use ALL CAPS (no spaces). value is the value the SHORTCUT takes on. It’s replaced by that value globally throughout the rest of your source code file. The value can be a number, equa­ tion, symbol, or string.

No semicolon is at the end of the line, but notice that the line absolutely must begin with a pound sign. This line appears at the beginning of your source code, before the main() function. 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. You can then use SPEED anywhere else in your program to represent 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. The shortcut word is usually written in ALL CAPS so as not to confuse it with a variable name. Other than that, the rules that apply to variable names typically apply to the shortcut words. Keep ’em short and simple is my recommendation. 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.\n”,SPEED);

And in this one: puts(GIRLFRIEND);

These lines may look strange, but they’re legit because the compiler knows what SPEED and GIRLFRIEND are shortcuts for. 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. String constants that are set up with #define are rare. Only if the string appears many times over and over in your program is it necessary to make it a constant. Otherwise, most programs use printf() or puts() to display text on the screen. You can also use math and other strangeness in a defined numeric con­ stant. This book doesn’t go into that subject, but something as obnox­ ious as the following line is entirely possible: #define SIZE 40*35

Here, the shortcut word SIZE is set up to be equal to 40*35, whatever that figures out to be. Using the #define thing isn’t required, and you’re not penalized if you don’t use it. Sure, you can stick the numbers in there directly. And, you can use variables to hold your constants. I won’t pout about it. You won’t go to C prison.

105

106

Part II: Run and Scream from Variables and Math

Real, live constant variables

Using #define to create a constant for use throughout your program is a handy thing to do. In fact, I recommend using it whenever you have some­ thing in your program that you figure may change. For example: #define NUMBER_OF_USERS 3 #define COLUMN_WIDTH 80 #define US_STATES 50

Each of these examples makes it possible to change aspects of your entire program merely by editing a single #define declaration. 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. To wit: const int senses = 6;

The preceding statement creates a variable named senses, but fixes that variable’s value at 6. The value cannot be changed or used for something else later in the program; if you try, a “read-only variable” error pops up. Most often you don’t see const used to create constant values. 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:. The const keyword ensures that this variable cannot be reused or its contents ever changed — a good idea for this type of variable.

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. It’s time to dive headlong into that hellfire of values and digits. Far down from the comfy safety of the int lie numbers large and loathsome. Terrifying values you can gingerly place into your puny programs. Numbers lethal and toxic, but which you can also tame, as long as you obey my gentle advice in this chapter. Fear not! Instead, don your asbestos suit and follow me. Watch your step.

There Are Numbers, and Then There Are Numbers Welcome to what will soon be one of many new, frustrating aspects of the C programming language. It’s known as the C Numeric Data Type Puzzle. Unlike in real life, where we can just pull any number out of the ethers and be joyously happy with it, in C you must pull numbers from specific parts of the ethers based on which type of number it is. 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 isn’t a “number type.” It’s a numeric data type, which is how you say “number type” if you work at the Pentagon. You have to tell the C compiler which type of number you’re using because it thinks about numbers differently from the way humans do. 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. Scientists have to know the precision when they send missiles to coun­ tries with opposing ideologies.) I know that this stuff is all alien to you. What most programmers want to do is say “I need a number variable — just give me one, quick — before this value slips out the back of the computer and becomes a government statistic!” But you have to think a little more before you do that. The most common numeric data type is the integer. If you’re going to work with decimal numbers, such as a dollar amount, you need the floating-point number. Keep reading.

Numbers in C

A number of different types of numbers are used in C — different numeric data types, so to speak. Table 9-1 lists them all, along with other statistical informa­ tion. Flag the table with a sticky note. This table is something you refer to now and again because only the truly insane would memorize it.

Table 9-1

C Numeric Data Types

Keyword

Variable Type

Range

char

Character (or string)

–128 to 127

int

Integer

–32,768 to 32,767

short

Short integer

–32,768 to 32,767

short int

Short integer

–32,768 to 32,767

Chapter 9: How to C Numbers

Keyword

Variable Type

Range

long

Long integer

–2,147,483,648 to 2,147,483,647

unsigned char

Unsigned character

0 to 255

unsigned int

Unsigned integer

0 to 65,535

unsigned short

Unsigned short integer

0 to 65,535

unsigned long

Unsigned long integer

0 to 4,294,967,295

float

Single-precision floating-point (accurate to 7 digits)

±3.4 ∞ 1038 to ±3.4 ∞ 10–38

double

Double-precision floating-point (accurate to 15 digits)

±1.7 ∞ 10–308 to ±1.7 ∞ 10308

The keyword is the C language keyword used to declare the variable type. If you have been reading the chapters in this book in order, you have used int, char, and float already. The variable type tells you which type of variable the keyword defines. For example, char defines a character (or string) variable, and int defines integers. C has many variable types, each of which depends on the type of number or value being described. The range tells you how big of a number fits into the variable type. For example, integers range from –32,768 up to 0 and up again to 32,767. Other types of variables handle larger values. This value may be differ­ ent on your compiler; use the values in Table 9-1 for reference only. Table 9-1 isn’t that complex. In all, C has really only four types of variables: char int float double The int can be modified with either short or long, and both char and int are modified with unsigned. The float and double variables are both floatingpoint, though the values held by double are larger.

109

110

Part II: Run and Scream from Variables and Math

Why use integers? Why not just make every number floating-point? Obviously, if you have a double-precision floating-point number that can handle, essentially, numbers up to one gazillion, why bother declaring any variables as integers? Heck, make everything a double-whammy floating point and be done with it! Sounds good. Is bad. Integers are truly the handiest and most common types of numeric variables. Oftentimes, you need only small, whole-number values when you’re program­ ming. Floating-point numbers are okay, but they require more overhead from the computer and take longer to work with. By comparison, integers are far quicker. For this reason, God saw fit to create integers (which He did on the third day, by the way).

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 signed and unsigned aspects are chewed over slowly later in this chapter.) The int (rhymes with “bent”) is a whole-number value, normally ranging from –32,768 to 32,767. It’s ideally put to use for small numbers without a fractional part. In some versions of C, you may see this value referred to as a short or short int. The long is a whole-number value, ranging from –2,147,483,648 to 2,147,483,647 — a big range, but not big enough to encompass the national debt or Madonna’s ego. This type of numeric variable is referred to as a long, or long int in some versions of C. You use the int and long keywords to declare integer variables. int is for smaller values; long is for larger values. The %d placeholder is used in the printf() function to display int vari­ ables. (You can also use the %i placeholder; refer to Table 24-2 in Chap­ ter 24.) int = short = short int long = long int Integer variables (int) are shorter, faster, and easier for the computer to deal with. If Soup for One were a variable, it would be an int. Use an int whenever you need a small, whole numeric value.

Chapter 9: How to C Numbers In some C compilers, the ranges for int and long int are the same. That’s because the compiler (usually a 32-bit model) can more efficiently handle long values than it can handle smaller int values. It’s merely technical junk; don’t memorize it or let it otherwise ruin your day. Negative numbers — why bother? Sometimes, you need them, but most of the time you don’t. See the next section. The char variable type can also be used as a type of integer, though it has an extremely small range. These variables are used mostly to store single characters (or strings), which is discussed somewhere else. (Give me a second to look.) Oh, it’s in Chapter 10.

Signed or unsigned, or “Would you

like a minus sign with that, Sir?”

I have this thing against negative numbers. They’re good only when you play Hearts. Even so, that’s justification because you may someday write a program that plays Hearts on the computer, in which case you will be in dire need of negative numbers (because you can write the program so that you always win). When you declare a numeric variable in C, you have two choices: signed and unsigned. Everything is signed unless you specifically type unsigned before the variable type: unsigned int shoot_the_moon = 26;

A signed type of number means that a variable can hold a negative value. The standard int variable can hold values from –32,768 up to 32,767. That’s half negative numbers, from –32,786 to –1, and then half positive numbers, from 0 up to 32,767. (Zero is considered positive in some cults.) An unsigned number means that the variable holds only positive values. This unsigned number moves the number range all up to the positive side — no negatives (the C language equivalent of Prozac). Your typical unsigned int has a range from 0 to 65,535. Negative numbers aren’t allowed. The int variable elephants holds the value 40,000. 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.

111

112

Part II: Run and Scream from Variables and Math

The whole painful spiel on why we have signed integers The signed-unsigned business all has to do with how numbers are stored inside a computer. 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. That’s counting in base 2 (ones and zeroes). Binary numbers are composed of bits, or binary digits. Suppose that your C language compiler uses two bytes to store an integer. Those two bytes contain 16 binary digits, or bits. (Eight bits are in a byte.) For example: 0111 0010 1100 0100

This value is written as 29,380 in decimal (the human counting system). In binary, the ones and zeroes represent various multiples of two, which can get quite complex before your eyes, but is like eating ice cream to the computer. Look at this number:

Table 9-2

0111 1111 1111 1111

It’s the value 32,767 — almost a solid bank of ones. If you add 1 to this value, you get the fol­ lowing amazing figure: 1000 0000 0000 0000

How the computer interprets this binary value depends on how you define your variable. For a signed value, a 1 in the far left position of the number isn’t a 1 at all. It’s a minus sign. The pre­ ceding number becomes –32,768 in binary math. If the variable is an unsigned value, it’s inter­ preted as positive 32,768. The deal with signed and unsigned numbers all depends on that pesky first bit in the computer’s binary counting tongue. If you’re working with a signed number, the first bit is the minus sign. Otherwise, the first bit is just another droll bit in the computer, happy to be a value and not a minus sign.

What Signed and Unsigned Variables Can Hold

Signed

Range

Unsigned

Range

char

–128 to 127

unsigned char

0 to 255

int

–32768 to 32,767

unsigned int

0 to 65,535

long

–2,147,483,648

unsigned long

0 to 4,294,967,295 to 2,147,483,647

Floating-point numbers (numbers with a decimal part or fractions) can be positive or negative without regard to any signed or unsigned nonsense. Floating-point numbers are covered in the following section. Normally, the differences between signed and unsigned values shouldn’t bother you.

Chapter 9: How to C Numbers Signed variables can be maddening and the source of frustration as far as creepy errors are concerned. It works like this: Suppose that you add 1 to a signed integer variable. If that variable already holds the value 32,767, its new value (after you add 1) is –32,768. Yes, even though you add a number, the result is negative. In that instance, you should be using an unsigned int variable type to avoid the problem. To use an unsigned variable and skirt around the negative-number issue, you must declare your variables by using either the unsigned int or unsigned long keyword. 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.

How to Make a Number Float

Two scoops of ice cream. . . . Integer variables are the workhorses in your programs, handling most of the numeric tasks. However, when you have to deal with fractions, numbers that have a decimal part, or very large values, you need a different type of numeric variable. That variable is the float. The float keyword is used to set aside space for a variable designed to con­ tain a floating-point, or noninteger, value. 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. The line ends in a semicolon. 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. Float is short for floating point. That term somehow refers to the decimal point in the number. For example, the following number is a floating-point value: 123.4567

An integer variable wouldn’t cut it for this number. It could be only 123 or 124. When you have a decimal, you need a floating-point variable.

113

114

Part II: Run and Scream from Variables and Math The range for floating-point numbers is quite large. With most C compilers, you can store any number in the range ±3.4 × 10–38 to ±3.4 × 1038. In English, that’s a value between negative 340 undecillion and positive 340 undecillion. An undecillion is a 1 with 36 zeroes after it. That’s a true, Mr. Spock-size value, though most numbers you use as floats are far less. Rules for naming variables are in Chapter 8. Noninteger values are stored in float variables. Even though 123 is an integer value, you can still store it in a float vari­ able. However. . . . float variables should be used only when you need them. They require more internal storage and more PC processing time and power than inte­ gers do. If you can get by with an integer, use that type of variable instead.

“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. We fly our UFO all over the galaxy, drink blue beer, and program in C on our computers. I’m Dan. Your name is Carl. 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. That is but a fraction of a light-year. 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. I’m the author of this book. You type the program, JUPITER.C, and you figure it out. Sheesh. #include int main() { float lightyear=5.878E12; float jupiter=483400000; float distance;

Chapter 9: How to C Numbers distance=jupiter/lightyear; printf(“Jupiter is %f light years from the sun.\n”,distance); return(0); }

Enter this program into your text editor. Be careful! Check spelling, odd char­

acters, other stuff. Save the file to disk as JUPITER.C.

Compile the program. If you see any errors, fix ’em up and recompile.

Run the program. The output looks something like this:

Jupiter is 0.000082 light years from the sun.

Carl: A mere stumble!

Dan: I’m still not walking it.

You use the float keyword to declare a floating-point variable. In scientific notation, which is how scientists sneak around the require­ ment of typing zeroes and commas, the length of a light year is written as 5.878E12. That means that the decimal in 5.878 should be shifted to the right 12 times. (The next section covers this ugly E-notation thing.) The variable jupiter is set equal to the mean distance between Jupiter and the sun, which is 484 million miles. In the source code, that’s 4834 fol­ lowed by 5 zeroes. There’s no need to mess with scientific notation here because the compiler can eat this relatively small-size number. (Anything over 100 billion usually requires the scientific E notation; you have to refer to your compiler’s manual to check the size of its mouth.) 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 number is extremely small. The %f placeholder is used in the printf() function to display floatingpoint values. The float variables are used in this program for two reasons: because of the humongous size of the numbers involved and because division usually produces a noninteger result — a number with a decimal part.

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. I assume that it’s okay to discuss this subject, because if you’re interested in programs that deal with these types of numbers, you probably already have one foot in the test tube. E notation is required in C (or even in the Excel spreadsheet) when some num­ bers get incredibly huge. Those numbers are floating-point numbers — or the floats, as you have come to know them. Integers don’t count. When you get a number over about eight or nine digits long, it must be expressed in E notation or else the compiler doesn’t eat it. For example, take the length of a light-year in miles: 5,878,000,000,000

That’s 5 trillion, 878 billion. In C, you don’t specify the commas, so the number should be written as follows: 5878000000000

That’s 5878 followed by nine zeroes. The value is still the same; only the commas — conveniently added to break up large numbers for your human eyeballs — have been removed. And though this number is within the range of a float, if you were to compile it, the compiler would moan that it’s too large. It’s not the value that bugs the compiler — it’s the number of digits in the number. To make the compiler understand the value, you have to express it by using fewer digits, which is where scientific notation comes in handy. Here’s the same value in E notation, as you specify it in the JUPITER.C program, from the pre­ ceding section: 5.878E12

Scientific, or E, notation uses a number in the following format: x.xxxxEnn

The x.xxxx is a value; it’s one digit followed by a decimal point and then more digits. Then comes big E and then another value (nn). To find out the number’s true size, you have to hop the decimal point in the x.xxxx value to the right nn places. Figure 9-1 illustrates how this concept works with the light-year value.

When you enter E numbers in the compiler, use the proper E format. To dis­ play the numbers in E format with printf(), you can use the %e placeholder. To see how it works, replace the %f in the JUPITER.C program with %e, save the change to disk, recompile, and run the result. The output is in E notation, something like the following: Jupiter is 8.223886e-05 light years from the sun.

If the E has a negative number in front of it, as shown in this example, you hop the decimal point to the left nn places, to indicate very small numbers. You would translate the preceding value into the following: .00008223886

Scientific, or E, notation is required when numbers contain too many digits for the C compiler to eat. A negative E number means that the value is very small. Remember to move the decimal point to the left rather than to the right when you see this type of number. Some compilers allow you to use the %E (big E) placeholder in printf() to display scientific-notation numbers with a big E in them.

117

118

Part II: Run and Scream from Variables and Math

Bigger than the Float, It’s a Double!

For handling really huge numbers, C has its largest data type, the double. 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 variables are declared by using the double keyword. 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. What’s precision? It deals with how decimal numbers, fractions, and very small and huge numbers are stored in a computer. Keep in mind that the computer uses only ones and zeroes to store information. For integers, that’s great. For non-integers, it means that some tomfoolery must take place. That tomfool­ ery works, but it tends to get inaccurate, or “fuzzy,” after a time, especially on the details. As an example, gawk at this number: 123.4567891234

That’s a float if I ever saw one. But if you define that value as a float variable in C, the computer can store it only as a single-precision value. It can accu­ rately hold only the first eight digits. The rest — it makes them up! To wit: 123.45678422231

The first eight digits are precise. The rest — eh? After the 8, the value gets screwy. It’s single precision in action. Double precision can be accurate to maybe 12 or 16 decimal places (but after that, it begins acting goofy as well). The moral of this story is twofold: First, if you have to make float calculations with your computer, remember that the number can be only so accurate. After about eight digits or so, the rest of the output is meaningless. Second, if you need precise calculations, use the double type of variable. It still has its prob­ lems, but it’s more precise than the float. You use the double keyword to declare a double-precision floating-point variable in your C programs. If you ever print a value — 123.456, for example — and the output you see is something like 123.456001, that extra 001 is the lack of precision the computer has when it’s dealing with floating-point numbers. For the most part, any extra value that’s added is insignificant, so don’t let it bug you.

Chapter 9: How to C Numbers Being accurate to eight digits is more than enough for most noninteger calculations. For sending people to Mars, however, I recommend the double. (I know that NASA reads these books intently.) Some compilers may offer quadruple-precision numbers with their own unique keywords and other rules and regulations. The greater the precision, the longer it takes the computer to deal with the numbers. Don’t use more precision than you have to.

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. Ugh. Now you have to plug your nose and plunge a little deeper into the murky waters of printf() formatting. Fortunately, this is about the only time you have to do that. Between the % and the f, you can insert some special formatting characters. They control the printf() function’s output and may help you get rid of some excess zeroes or trim up the number that is displayed. 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. The following placeholder displays the float number by using only two deci­ mal places. It’s ideal for displaying dollar amounts. Without it, you may have $199.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: %.4f

This placeholder formats floating-point numbers to display four digits after the decimal point. If the value isn’t that small, zeroes pad out the four deci­ mal places. The following format information tells printf() to display the number by using six digits — which includes the decimal point: %6f

119

120

Part II: Run and Scream from Variables and Math No matter how big the number is, it’s always displayed by using six digits. Rather than leading zeroes, the number is padded on the left with spaces. The number 123 is displayed as 123.

This line begins with two spaces, or is indented two spaces, depending on how you look at it. Sometimes the %f may display a number that looks like this: 145000.000000

In that case, you can trim up the number by using either %.2f, which displays only two zeroes after the decimal point, or something like %6f, which limits the output to only six digits. An alternative to messing with numbers and other characters between the % and little f is to use the %e placeholder. It displays numbers in sci­ entific format, which is usually shorter than the %f placeholder’s output. Then there’s the %g placeholder. That thing displays a floating-point number in either the %f or %e (scientific) format, depending on which is shorter. Yes, I know that this chapter is short on examples. But numbers are boring. So there.

Chapter 10

Cook That C Variable

Charred, Please

In This Chapter Using the char declaration Assigning characters to variables Understanding getchar() and putchar() Treating char as a tiny integer variable

T

oo many C language books seem to fixate on numbers and avoid com­ pletely the other type of variable — the character, or string, variable. It’s definitely more fun. Rather than hold values — values, bah! — character vari­ ables hold individual characters or letters of the alphabet and complete strings of text. This certainly opens the floodgates of creativity over pounding the sand with numbers. This chapter rounds off your variable declaration journey with an official hello to the char variable, suited for storing both single characters and strings of text. In this chapter, it’s only single characters you have to worry about.

The Other Kind of Variable Type, the char Though I talk about both single-character and string variables, C language has only one variable type, the char, which is defined by the keyword char. And I think, though I’m not certain, that it’s pronounced “care” and not “char,” as in “charred beyond all recognition.”

122

Part II: Run and Scream from Variables and Math

Single-character variables

Like a string of text, the single-character variable is declared by using the char keyword. Unlike a string, the single-character variable holds only one character — no more. In a way, the character variable is like a padded cell. The string variable is merely several padded cells one after the other — like an asylum. The char keyword is used to set aside storage space for a single-character variable. 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. In the following format, you can predefine a single-character value: char var=’c’;

Typing those hard-to-reach characters Some characters can’t be typed at the keyboard or entered by using escape sequences. 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. It’s possible — just a little technical. Follow these steps: 1. Look up the character’s secret code value — its ASCII or extended ASCII code number. 2. Convert that code number into base 16, the hexadecimal, or “hex,” system. (That’s why hexadecimal values are usually shown in the ASCII tables and charts.) 3. Specify that hex value, which is two digits long, after the \x escape sequence.

4. Remember to enclose the entire escape sequence — four characters long — in single quotes. Suppose that you want to use the British pound symbol, £, in your program. That character’s secret code number is 156. Look it up in Appendix B. You can see that the hexadecimal value is 9C. (Hex numbers contain letters.) So you specify the following escape sequence in your program: ‘\x9C’

Notice that it’s enclosed in single quotes. The C, or any other hexadecimal letter, can be upperor lowercase. 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.

Chapter 10: Cook That C Variable Charred, Please char is followed by a space. The name of the variable you’re creating, var, is followed by an equal sign and then a character in single quotes. The statement ends in a semicolon.

Inside the single quotes is a single character, which is assigned to the vari­ able var. You can specify any single character or use one of the escape sequences to specify a nontypable character, such as a double-quote, a single quote, or the Enter key press. (See Table 24-1 in Chapter 24 for the full list of escape sequences; also see the nearby sidebar, “Typing those hard-toreach characters.”) The single-character variable is ideal for reading one character (obviously) from the keyboard. 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. This is how a menu system works, how you can type single-key commands without having to press Enter, and how you can write your own keyboard-reading programs. Oh, it can be fun.

Char in action

The following statement creates the character variable ch for use in the pro­ gram (you can also predefine the variable if need be): char ch;

This next statement creates the character variable x and assigns to it the char­ acter value ‘X’ (big X): char x=’X’;

When you assign a character to a single-character variable, you use single quotes. It’s a must! Some characters, you can’t really type at the keyboard. For example, to pre­ define a variable and stick the Tab key into it, you use an escape sequence: char tab=’\t’;

This statement creates the character variable tab and places in that variable the tab character, represented by the \t escape sequence. Single-character variables are created by using the char keyword. Don’t use the square brackets when you’re declaring single-character variables.

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. Don’t use double quotes. You can assign almost any character value to the character variable. Special, weird, and other characters can be assigned by using the escape sequences. Information about creating string variables is presented in Chapter 4. This chapter deals primarily with single-character variables.

Stuffing characters into character variables You can assign a character variable a value in one of several ways. The first way is to just stuff a character in there, similar to the way you stuff a value into a numeric variable or your foot into a sock. 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. The statement ends in a semicolon. (I assume that key was defined as a character variable by using the char key; statement, earlier in the program.) In addition to single characters, you can specify various escape sequences (the \-character things), values, and whatnot. As long as it’s only one charac­ ter long, you’re hunky-dory. Another way to stick a character into a single-character variable is to slide one from another character variable. Suppose that both old and new are charac­ ter variables. The following is acceptable: old=new;

The character in new squirts through the equal sign and lands in the charac­ ter variable old. After the preceding statement, both variables hold the same character. (It’s a copy operation, not a move.) You can assign single characters to single-character variables. But. . . . You still cannot use the equal sign to put a string of text into a string variable. Sorry. It just can’t be done.

Chapter 10: Cook That C Variable Charred, Please

Reading and Writing Single Characters

This book introduces you to two C language functions used to read text from the keyboard: scanf() and gets(). Both read text from the keyboard, usually as full sentences. However, scanf() can be used to read in single characters, which is part of its charm — and flexibility: scanf(“%c”,&key);

In this format, scanf() reads the keyboard for a single character, specified by the placeholder %c. That value is stored in the char variable key, which you can assume was already declared earlier in the program. To wit: #include int main() { char key; puts(“Type your favorite keyboard character:”); scanf(“%c”,&key); printf(“Your favorite character is %c!\n”,key); return(0); }

Press a key, such as m (or whatever your favorite is), and then press the Enter key. You see this: M Your favorite character is M!

The M key is read from the keyboard, stored in the char variable key, and then displayed by printf(). Yes, you have to press the Enter key to finish your input — that’s the way the scanf() function works. You can type a whole string of text, but only the first character that’s typed is read by scanf() as the favorite key.

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. The C language also has a function named getchar(), which is used specifically to read a single character from the keyboard. Here’s the format: var=getchar();

var is a character variable. It holds whatever character is typed at the key­ board. var is followed by an equal sign and then getchar and two parenthe­ ses hugging nothing. This function is a complete statement and ends with a semicolon. The getchar() function causes your program to pause and wait for a key to be typed at the keyboard. getchar() sits and waits. Sits and waits. Sit. Wait. Sit. Wait. When a key is typed and then Enter is pressed, that character’s “value” slides across the equal sign and is stored in the character variable. The following is the update to the FAVKEY1.C program, this time replacing the sordid scanf() function with the better getchar() function: #include 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.C, changing only Line 8 and replacing the scanf() function with getchar(), as just shown. Save the new file to disk as FAVKEY2.C. 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. Yes, it seems silly that you have to type Enter when entering a single char­ acter. That’s just the way getchar() works. (And I hate it.) There are ways to read the keyboard more interactively, where pressing the Enter key isn’t required. I cover these methods in my book C All-inOne Desk Reference For Dummies (Wiley).

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. Here’s the format, though you probably could have guessed it: putchar(c); c can be either a single-character variable or a character constant in single quotes: putchar(‘c’);

The character ‘c’ is displayed on the screen. The following program shows how putchar() can be put to use in tossing up characters on the screen: #include int main() { puts(“Press Enter:”); getchar(); putchar(‘H’); putchar(‘e’); putchar(‘l’); putchar(‘l’); putchar(‘o’); putchar(‘!’); putchar(‘\n’); return(0); }

Note that getchar() is used here merely to read the Enter key press; any value returned by getchar() isn’t stored. When used in this format, getchar() still returns a value, but because it’s not stored in a variable, the value is “lost.” That’s perfectly okay.

127

128

Part II: Run and Scream from Variables and Math Beyond the getchar() dilemma, the program uses seven putchar() functions to display Hello! (plus a newline character) to the screen. It’s a rather silly use of putchar(), but it works. The putchar() function is used to display a single character on the screen. You can also specify a character as an escape sequence or a code value with putchar() (see the next section).

Character Variables As Values

If you want, you can live your life secure in the knowledge that the char key­ word sets aside storage space for single-character variables and strings. That’s all well and good, and it gets you an A on the quiz. You can stop reading now, if you want. The horrible truth is that a single-character variable is really a type of integer. It’s a tiny integer, but an integer nonetheless. The reason that it isn’t obvious is that treating a char as an integer is really a secondary function of the singlecharacter variable. The primary purpose of single-character variables is to store characters. But they can be used as integers. It’s twisted, so allow me to explain in detail. The basic unit of storage in a computer is the byte. Your computer has so many bytes (or megabytes) of memory, the hard drive stores so many giga­ bytes, and so on. Each one of those bytes can be looked at as storing a single character of information. A byte is a character. Without boring you with the details, know that a byte is capable of storing a value, from 0 to 255. That’s the range of an unsigned char integer: from 0 to 255 (refer to Table 9-1, in Chapter 9). Because a character is a byte, the char can also be used to store those tiny integer values. When the computer deals with characters, it doesn’t really know an A from a B. It does, however, know the difference between 65 and 66. Internally, the computer uses the number 65 as a code representing the letter A. The letter B is code 66. In fact, all letters of the alphabet, number characters, symbols, and other assorted jots and tittles each have their own character codes. The coding scheme is referred to as ASCII, and a list of the codes and characters is in Appendix B. Essentially, when you store the character A in a char variable, you place the value 65 into that variable. Internally, the computer sees only the 65 and, lo, it’s happy. Externally, when the character is “displayed,” an A shows up. That satisfies you and me, supposing that an A is what we want.

Chapter 10: Cook That C Variable Charred, Please This is how char variables can be both integers and characters. The truth is, they are integers. However, they are treated like characters. The following program, WHICH.C, reads a character from the keyboard and displays it by using the printf() function. The trick with WHICH.C is that the character is displayed as both a character and a numeric, integer value. Such duality! Can you cope? #include int main() { char key; printf(“Press a key on your keyboard:”); key=getchar(); printf(“You pressed the ‘%c’ key.\n”,key); printf(“Its ASCII value is %d.\n”,key); return(0); }

Save the file to disk, naming it WHICH.C. Compile WHICH.C. If you get any errors, double-check the source code, fix it up, and recompile. Run the final program. If you press the A key (and then Enter), the output on your screen looks something like this: Press a key on your keyboard:A You pressed the ‘A’ key. Its ASCII value is 65.

The second printf() statement displays the key variable by using the %c placeholder. This placeholder tells printf() to display the variable as a char­ acter. In the third printf() statement, the variable is displayed by using the %d placeholder. That one tells printf() to display the variable as an integer value — which it does. All letters of the alphabet, symbols, and number keys on the keyboard have ASCII codes. ASCII code values range from 0 to 127. Code values higher than 127 — from 128 to 255 — are called extended ASCII codes. Those characters aren’t standard on all computers, though they’re pretty consistent on Windows PCs. It’s just a technical snit. Appendix B lists all the ASCII characters and their values. Chapter 13 shows you how to “compare” one letter or ASCII character with another. What’s being compared is really the character’s code value, not its aesthetics.

129

130

Part II: Run and Scream from Variables and Math

Part III

Giving Your Programs the Ability to Run Amok

T

In this part . . .

he programs illustrated in the ﬁrst two parts of this book have been top-down. That is, they are executed one line after another, from top to bottom. They make no deviations and have no change in the pattern, no creativ­ ity, no choice. Boring! But computer programs can do more than that. To really make a program run amok, you can place a deci­ sion machine inside of it. That decision machine lets the program do one thing or another based on a comparison, such as “If the user types L, then go left and get eaten by the hungry elf.” It’s not a choice that the computer makes; the computer is dumb. But it’s an alternative, which means that the program is capable of more than just chomping through instructions, one after the other. 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. Pirates. Ghosts.

Screaming Dolls. Disneyland needs math in order to terrify and thrill children

of all ages. Ludwig von Drake would host. But I digress.

This chapter really isn’t the dreadful math chapter, but it’s my first lecture

that dwells on math almost long enough to give you a headache. Don’t panic!

The computer does all the work. You’re only required to assemble the math

in the proper order for the answers to come out right. And, if you do it wrong,

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

recriminations. No snickering from the way-too-smart female exchange stu­

dent from Transylvania.

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). These symbols and scribbles make basic math happen in a C program.

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. In this example: result = 67 * 8;

the variable result (which can be either an integer or a float variable) contains the result of multiplying 67 by 8: odds = 45/122;

The float variable odds contains the result of dividing 45 by 122: In all cases, the math operation to the right of the equal sign is per­ formed first. The math is worked from left to right by the C compiler. The value that results is placed in the numeric variable. Work with values and variables: score = points*10;

The variable score is set equal to the value of the variable points times 10. Work with just about anything; functions, values, variables, or any combination: height_in_cm = atoi(height_in_inches)*2.54;

The variable height_in_cm is set equal to the value returned by the atoi function times 2.54. The atoi() function manipulates the variable height_in_inches (which is probably a string input from the keyboard).

Chapter 11: C More Math and the Sacred Order of Precedence The math part of the equation is calculated first and is worked from left to right. The result is then transferred to the variable sitting on the left side of the equal sign.

The old “how tall are you” program

You can use “the power of the computer” to do some simple yet annoying math. As an example, I present the HEIGHT.C program, with its source code shown next. This program asks you to enter your height in inches and then spits back the result in centimeters. Granted, it’s a typically dull C language program. But, bear with me for a few pages and have some fun with it. Enter this trivial program into your editor: #include #include int main() { float height_in_cm; char height_in_inches[4]; printf(“Enter your height in inches:”); gets(height_in_inches); height_in_cm = atoi(height_in_inches)*2.54; printf(“You are %.2f centimeters tall.\n”,height_in_cm); return(0); }

Be careful with what you type; some long variable names are in there. Also, it’s height, not hieght. (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.C. Compile the program. Watch for any syntax or other serious errors. Fix them if they crop up. Run the HEIGHT program. Your output looks something like this: Enter your height in inches:60 You are 152.40 centimeters tall.

If you’re 60 inches tall (5 feet exactly), that’s equal to 152.40 centimeters — a bigger number, but you’re still hovering at the same altitude. The program is good at converting almost any length in inches to its corresponding length in centimeters.

135

136

Part III: Giving Your Programs the Ability to Run Amok Height. It has e before i. It’s another example of why English is the worstspelled language on the planet. (It’s your number-one typo possibility if you get a syntax error in the program.) The atoi() function reaches into the string you enter and pulls out an integer value. And, it’s atoi(), not atio() (another reason, though invalid, to hate English spelling). The atoi() function translates the value held in the string variable,

height_in_inches, into an integer. Then that value is multiplied by

2.54. (The asterisk is used for multiplication.) The result is then slid through the equal sign and stored in the float variable, height_in_cm. The value 2.54 is obviously a float because it contains a decimal part. height_in_inches is an integer because that’s the type of value the atoi() function returns. When you multiply an integer by a float, how­ ever, the result is a float. That’s why the height_in_cm variable is a float. An inch has 2.54 centimeters in. It’s not that this knowledge gets you anywhere, at least not in the United States. However, if you’re on Jeopardy! and the Final Jeopardy answer is 2.54, you’ll know the ques­ tion. (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.) A centimeter equals 0.39 inches. A centimeter is really about as long as your thumbnail is wide —as long as you don’t have colossal thumbs, of course.

Unethical alterations to the old “how tall are you” program Though I’m not standing behind you, I can clearly see the HEIGHT.C program source code sitting in your editor. Good. Change Line 11 as follows: height_in_cm = atoi(height_in_inches)*2.54*1.05;

After the 2.54 and before the semicolon, insert *1.05 (“times one point-ohfive”). This increases your height by five-hundredths of a centimeter for each centimeter you have in height. The result? Wait! Save the file and recompile it. Then run it again: Enter your height in inches:60 You are 160.02 centimeters tall.

That may not mean much to you. But suppose that you’re corresponding with some French person who’s romantically interested in 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.02 centimeters tall. That means nothing to an American, but it means that you’re three whole inches taller in France. If you were 5'10" (70 inches), the program would produce the following: Enter your height in inches:70 You are 186.69 centimeters tall.

Now, you’re 186.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. For the most part, people who run programs want accurate results. However, it does show you the following: height_in_cm = atoi(height_in_inches)*2.54*1.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. That’s multiplied by 2.54, and the result is multiplied again by 1.05. Having a long mathematical formula is perfectly okay in C. You can add, mul­ tiply, divide, and whatnot all the time. To ensure that you always get the result you want, however, you must pay special attention to something called the order of precedence. That’s the topic of a section later in this chapter. An equation in C can have more than two items. In fact, it can have a whole chorus line of items in it. The items must all be on the right, after the equal sign. To increase the height value by .05 (five-hundredths, or 5 percent), the number must be multiplied by 1.05. If you just multiply it by .05, you decrease it by 95 percent. Instead, you want to increase it by 5 percent, so you multiply it by 105 percent, or 1.05. I stumbled on this knowledge accidentally, by the way.

The Delicate Art of Incrementation

(Or, “Just Add One to It”)

The mathematical concept of “just add 1 to it” is called incrementation. 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. These are examples of incrementation.

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 involves using this funky equation: i=i+1;

This math problem serves one purpose: It adds 1 to the value of the variable i. It looks funny, but it works. Suppose that i equals 3. Then i+1 (which is 3 + 1) equals 4. Because the right side of the equal sign is worked out first in C, the value 4 is slid over and put into the i variable. The preceding statement increments the value of the i variable by 1. You can also use the equation to add more than 1 to a value. For example: i=i+6;

This equation increments the value of the i variable by 6. (Purists will argue, though, that the word increment means strictly to “add one to.” 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. No, that’s not incrimination. Different subject. Some examples of incrementing values are altitude as a plane (or space­ ship) climbs; miles on an odometer; your age before and after your birthday; the number of fish the cat has eaten; and your weight over the holidays. Incrementation — i=i+1 — works because C figures out what’s on the right side of the equal sign first. i+1 is done first. Then it replaces the original value of the i variable. It’s when you look at the whole thing all at once (from left to right) that it messes with your brain.

Unhappily incrementing your weight

The following program is LARDO.C, a rather rude interactive program that uses math to increment your weight. You enter what you weigh, and then LARDO calculates your newfound bulk as you consume your holiday feast:

Type the preceding source code into your text editor. The only truly new material in this example is the w=w+1 equation, which increments the value of the w variable by one. The final equation, w=w+8, adds eight to the value of the w variable. Check your typing and be mindful of semicolons and double quotes. Save the file to disk as LARDO.C. Compile LARDO.C. Fix any errors, if need be. The following sample of the program’s final run uses 175 as the user’s weight: Enter your weight:175 Here is what you weigh now: 175 Your weight after the potatoes: 176 Here you are after the mutton: 177 And your weight after dessert: 185 pounds! Lardo!

This program doesn’t need to be insulting — but what the hey! The idea in this example is to show how the w=w+1 equation is used to add 1 to the value of a variable. It’s called incrementation. (It’s what God does to your weight every morning that you lug your pudgy legs onto the scale.) Yeah, 175 pounds! I’m sure that you typed an equally modest value rather than something more representative of your true girth.

139

140

Part III: Giving Your Programs the Ability to Run Amok

Bonus program! (One that may even have a purpose in life) Monopoly is perhaps one of the greatest board games ever invented, and it can be terrific fun — especially when you own rows of hotels and your pitiful opponents land on them like witless flies on a discarded all-day sucker. 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. You count up all your houses and multiply that number by $40 and all the hotels by $115 (which is a strange number), and then you add the two values. It’s a terrible thing to do to one’s brain in the middle of a Monopoly game. But the mental drudgery can be easily abated by a simple computer program, one such as ASSESSED.C: #include #include 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.\n”,total); return(0); }

Carefully type this program into your editor on a new screen. Double-check your semicolons, parentheses, and quotes. Then save it to disk as ASSESSED.C. Compile! Fix any errors, if need be. Then run the program. Suppose that you have nine houses and three hotels. Here’s what your output looks like: Enter the number of houses:9 Enter the number of hotels:3 You owe the bank $705.

Chapter 11: C More Math and the Sacred Order of Precedence Amazing how easy the computer could figure that out! Of course, at this point in the game, you can easily afford the $705 in funny money. All you need is for some poor sap to land on St. Charles Place with its hotel, and you make the money back jiffy-pronto. 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. The mathematical computation in Line 17 works because of something called the Sacred Order of Precedence, which is covered in the very next section. You may think, and rightly so, that the total displayed by the program should be a float variable. After all, dollar amounts usually have a deci­ mal part: $705.00 rather than $705. But, in this case, because all the values are integers, it just makes more sense to stick with a total inte­ ger variable. Keep in mind that integers are faster, which is especially apparent in larger programs.

The Sacred Order of Precedence

Precedence refers to what comes first. 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. The order of precedence is a double redundancy (which in itself is redundant several times over). It refers to which of the mathematical operators has prior­ ity over the others. For example, a plus sign just can’t march into the middle of a group of numbers and expect to add things the way it wants to. In C, other mathematical operations are done before addition. It’s just proper.

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. Yes, most dentists would rather be pulling teeth — even their own. The preceding problem isn’t really a problem for you, though. The computer fig­ ures the answer. 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. Does the compiler force the computer to do that for you automatically? Or should the value 90 be placed into the answer variable? Ninety? Yes, the value of the answer variable is 90. This all has to do with My Dear Aunt Sally and the order of precedence. Before getting into that, I show you the following program, DENTIST.C, which you can type to prove that the answer is 90 and not 50: #include int main() { printf(“%d”,100+5*2-60/3); return(0); }

Enter this short and sweet program into your editor. Compile it. Run it. It’s a printf() statement, with only %d in double quotes. That’s followed by a comma and then the math question from the dentistry final. Run the program. The result should shock you: 90

The order of your mathematical equations is important. Not knowing how the C compiler works out its math means that you may not get the answer you want. That’s why you have to know the order of precedence and, more importantly, My Dear Aunt Sally. When the DENTIST.C program runs, the computer works on the equation 100+5*2-60/3 first in the printf() function. The result is then passed over to the fill-in-the-blanks %d and is displayed on the screen. I could have expanded DENTIST.C to declare the answer integer vari­ able, assign the value to that variable, and then use printf() to display the variable’s contents. But, naaah. That would be too long of a program. The C language is full of short ways to do things. The printf() state­ ment in DENTIST.C is just one example of a scrunched-up C program.

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.” In this case, My Dear Aunt Sally is a mnemonic for

Chapter 11: C More Math and the Sacred Order of Precedence Multiplication Division Addition Subtraction MDAS is the order in which math is done in a long C language mathematical equation — the order of precedence. 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. Things just aren’t from left to right any more. Figure 11-1 illustrates how the mathematical example in the preceding section figures out to be 90.

answer = 100 + 5 * 2 - 60 / 3;

Figure 11-1: How the C compiler figures out a long math function.

answer = 100 +

10

- 60 / 3;

answer = 100 +

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 multiplication and division are next to each other, as in the preceding line, it goes from left to right. When the computer is finished counting its thumbs and the preceding state­ ment is resolved, the answer variable contains the value 25. You can prove it by editing the DENTIST.C program and replacing the math that’s already there, in the preceding math equation. Recompile and run the program to confirm that the answer is 25. Or, just trust me and let it go at that.

143

144

Part III: Giving Your Programs the Ability to Run Amok My Dear Aunt Sally. Multiplication (*), division (/), addition (+), and sub­ traction (–) are done in that order in the C language’s long mathematical equations. The reason that the order of precedence is important is that you must organize your mathematical equations if you expect the proper answer to appear. The ASSESSED.C program, from the preceding section, also takes advan­ tage of the order of precedence: total=houses*40+hotels*115;

The number of houses times 40 is worked out first, and then hotels times 115 is done second. The last step is to add the two. A way to control the order of precedence is by using parentheses, as dis­ cussed in the obviously named section “Using parentheses to mess up the order of precedence,” later in this chapter.

The confounding magic-pellets problem

I hated those math-class story problems when I was a kid. In fact, I still do. In any event, here I am, in my adulthood, making up something like the following: Suppose that you have 100 of these magic pellets. They double in quantity every 24 hours. After a day, you have 200. But, first you have to give 25 to the butcher in exchange for three dozen lamb’s eyeballs for a casserole you want to surprise your spouse with. If so, how many magic pellets would you have the next day? Don’t bother stewing over the problem. The equation is 100 - 25 * 2;

That’s 100 magic pellets minus 25 for the eyeballs and then times 2 (doubled) the next day. In your head, you can figure that 100 minus 25 is 75. Multiply 75 by 2 and you have 150 magic pellets the next day. But in C, this just wouldn’t work; the order of precedence (that Sally person) would multiply 25 by 2 first. That would calculate to 50 magic pellets the next day. What a gyp! The following C program, PELLETS.C, illustrates how the magic-pellet prob­ lem is confounded by C’s order of precedence. This program is a somewhat more complex version of the basic DENTIST.C program, presented earlier in this chapter:

Enter this program in your editor. Double-check everything. Save the file to disk as PELLETS.C. Compile PELLETS.C. Fix any errors. Run the PELLETS program. Your output looks like this: Tomorrow you will have 50 magic pellets.

Uh-huh. Try explaining that to the IRS. Your computer program, diligently entered, tells you that there are 50 pellets, when tomorrow you will really have 150. The extra 100? They were lost to the order of precedence. In the PELLETS.C program, addition must come first. The way that works is by using parentheses.

Using parentheses to mess up the order of precedence My Dear Aunt Sally can be quite overbearing. She’s insistent. Still, even though she means well, she goofs up sometimes. In the PELLETS.C program, for exam­ ple, she tells the C compiler to multiply 25 by 2 first and then subtract the result from 100. Anyone who reads the problem knows that you must subtract 25 from 100 first and then multiply what’s left by 2. The problem is convincing the C compiler — and Aunt Sally — how to do that. You can circumvent the order of precedence by using parentheses. When the C compiler sees parentheses, it quickly darts between them, figures out the math, and then continues with multiplication, division, addition, and subtrac­ tion, in that order, from left to right, outside the parentheses. To fix the PELLETS.C program, you have to change the seventh line to read: total=(100-25)*2;

145

146

Part III: Giving Your Programs the Ability to Run Amok The C compiler does the math in the parentheses first. So, at once, 25 is sub­ tracted by 100, to equal 75. Then, the rest of the math is done: 75 times 2 is 150 — the correct number of magic pellets. I beg of you to make the preceding change to Line 7 in your PELLETS.C pro­ gram. Stick the left parenthesis before 100, and insert the right one after 25. Save the changes to disk, recompile, and then run the program. The result should please you: Tomorrow you will have 150 magic pellets.

The math that appears in the parentheses is always done first. It doesn’t matter whether it’s addition, subtraction — whatever. It’s always done first in the equation. Inside the parentheses, the math is still worked from left to right. Also, multiplication and division still have priority inside the parentheses. It’s just that whatever is in the parentheses is done before whatever is out­ side. Here’s a summary for you: 1. Work inside the parentheses first. 2. Multiplication and division first, and addition and subtraction second. 3. Work from left to right. If you have ever worked with complex spreadsheet equations, you’re familiar with the way parentheses can be used to force some math oper­ ations to be done before others. 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. Such value. Yeah, you can even put parentheses inside parentheses. Just make sure that they match up; rogue parentheses produce syntax errors, just like missing double quotes and absent curly braces do. It doesn’t matter where the parentheses are in the math equation; what’s in them is always done first. For example: total=2*(100-25);

In this statement, 100 minus 25 is calculated first. The result, 75, is then multiplied by 2. This holds true no matter how complex the equation gets — though I’m afraid that you may run away or faint if I show you a more complex example.

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 another keyword in the C programming language, one that you can use in your program to make decisions — although it really makes comparisons, not decisions. It’s the program that decides what to do based on the results of the comparison. This chapter is about adding decision-making power to your programs by using the if command. Keep in mind that the computer doesn’t decide what to do. Instead, it follows a careful path that you set down for it. 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.

If Only. . . . 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. These are all events that happen, which the computer must deal with.

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. The decisions are based on a comparison. For example: If the contents of variable X are greater than variable Y, scream like

they’re twisting your nose.

If the contents of the variable calories are very high, it must taste very good. If it ain’t broke, don’t fix it. If Doug doesn’t ask me out to the prom, I’ll have to go with Charley. All these examples show important decisions, similar to those you can make in your C programs by using the if keyword. However, in the C programming language, the if keyword’s comparisons are kind of, sort of — dare I say it? — mathematical in nature. 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. The if keyword makes the comparison, and if the comparison is true, your program does a particular set of tasks. if is a keyword in the C programming language. It allows your programs to make decisions. if decides what to do based on a comparison of (usually) two items. The comparison that if makes is mathematical in nature: Are two items equal to, greater than, less than — and so on — to each other? If they are, a certain part of your program runs. If not, that part of the program doesn’t run. The if keyword creates what is known as a selection statement in the C language. 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. Selection statement. Impress your friends with that term if you can remember it. Just throw your nose in the air if they ask what it means. (That’s what I do.)

The computer-genie program example

The following program is GENIE1.C, one of many silly computer guess-thenumber programs you write when you find out how to program. Computer scientists used to play these games for hours in the early days of the com­ puter. They would probably drop dead if we could beam a Sony PlayStation back through time.

Chapter 12: C the Mighty if Command What GENIE1.C does is to ask for a number, from 0 through 9. You type that number at the keyboard. Then, using the magic of the if statement, the com­ puter tells you whether the number you entered is less than 5. This program was a major thigh-slapper when it was first written in the early 1950s. Enter the following source code into your text editor. The only new stuff comes with the if statement cluster, near the end of the program. Better double-double-check your typing. #include #include 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(number3) { printf("Where is your neck?"); } printf("something else");

if is followed by a set of parentheses in which a comparison is made. The comparison is mathematical in nature, using the symbols shown in Table 12-1. What’s being compared is usually the value of a variable against a constant value, or two variables against each other. (See Table 12-1 for examples.)

If the result of the comparison is true, the statement (or group of statements) between the curly braces is executed. If the result is false, the stuff in the curly braces is conveniently skipped over — ignored like a geeky young lad at his first high school dance and with a zit the size of Houston on his chin. Yes, the curly braces that follow if can contain more than one statement. And, each of the statements ends with a semicolon. All are enclosed in the curly braces. It’s technically referred to as a code block. It shows you which statements “belong” to if. The whole darn thing is part of the if statement.

Table 12-1

Operators Used in if Comparisons

Comparison

Meaning or Pronunciation

“True” Examples

0

= 2

!=

Not equal to

1 != 0 4 != 3.99

The GENIE1 program, from the preceding section, uses this if statement: 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. The following modification to the GENIE1.C program doesn’t change the if comparison, as in the previous examples. Instead, it shows you that more than one statement can belong to if: if(number symbol is greater than because the big side comes first; the < is less than because the lesser side comes first. The symbols for less than or equal to and greater than or equal to always appear that way: =. Switching them the other way generates an error. The symbol for “not” in C is the exclamation point. So, != means “not equal.” What is !TRUE (not-true) is FALSE. “If you think that it’s butter, but it’s !.” No, I do ! want to eat those soggy zucchini chips. When you’re making a comparison to see whether two things are equal, you use two equal signs. 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.” For example: if(x==5)

Read this statement as “If the value of the x variable is equal to 5, then. . . .” If you think “equals,” you have a tendency to use only one equal sign — which is very wrong.

153

154

Part III: Giving Your Programs the Ability to Run Amok If you use one equal sign rather than two, you don’t get an error; how­ ever, the program is wrong. The nearby Technical Stuff sidebar attempts to explain why. If you have programmed in other computer languages, keep in mind that the C language has no 2ewd or fi word. The final curly brace signals to the compiler that the if statement has ended. Also, no then word is used with if, as in the if-then thing they have in the BASIC or Pascal programming language.

A question of formatting the if statement

The if statement is your first “complex” C language statement. The C lan­ guage has many more, but if is the first and possibly the most popular, though I doubt that a popularity contest for programming language words has ever been held (and, then again, if would be great as Miss Congeniality but definitely come up a little thin in the swimsuit competition). Though you probably have seen the if statement used only with curly braces, it can also be displayed as a traditional C language statement. For example, consider the following — one of the modifications from the GENIE1 program: if(number==5) { printf(“That number is 5!\n”); }

In C, it’s perfectly legitimate to write this as a more traditional type of state­ ment. To wit: if(number==5) printf(“That number is 5!\n”);

This line looks more like a C language statement. It ends in a semicolon. Everything still works the same; if the value of the number variable is equal to 5, the printf() statement is executed. If number doesn’t equal 5, the rest of the statement is skipped. 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.

Chapter 12: C the Mighty if Command

Clutter not thy head with this comparison nonsense The comparison in the if statement doesn’t have to use any symbols at all! Strange but true. What the C compiler does is to figure out what you have put between the parentheses. Then it weighs whether it’s true or false.

No, you need two equal signs for that. Instead, what happens between these parentheses is that the numeric variable input is given the value 1. 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. However, you can stick just about anything — any valid C statement — between the paren­ theses and the compiler determines whether it works out to true or false. For example:

The C compiler obeys this instruction, stuffing 1 into the input variable. Then, it sits back and strokes its beard and thinks, “Does that work out to be true or false?” Not knowing any better, it figures that the statement must be true. It tells the if keyword, and the cluster of statements that belong to the if statement are then executed.

if(input=1)

input=1;

This if statement doesn’t figure out whether the value of the input variable is equal to 1.

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. You should pay more taxes if you’re taller and more taxes if it’s warmer outside. Yessir, it would be hard to dodge this one. This problem is ideal for the if keyword to solve. You pay taxes based on either your height or the temperature outside, multiplied by your favorite number and then 10. Whichever number is higher is the amount of tax you pay. To figure out which number is higher, the program TAXES.C uses the if keyword with the greater-than symbol. It’s done twice — once for the height value and again for the temperature outside:

This program is one of the longer ones in this book. Be extra careful when you’re typing it. It has nothing new in it, but it covers almost all the informa­ tion I present in the first several chapters. Double-check each line as you type it into your editor. Save the file to disk as TAXES.C. Compile TAXES.C. Fix any errors you see. Run the program: Enter your height in inches:

Type your height in inches. Five feet is 60 inches; six feet is 72 inches. The average person is 5'7" tall or so — 67 inches. Press Enter. What temperature is it outside?

Right now, in the bosom of winter in the Pacific Northwest, it’s 18 degrees. That’s Fahrenheit, by the way. Don’t you dare enter the smaller Celsius number. If you do, the IRS will hunt you down like a delinquent country music star and make you pay, pay, pay.

Chapter 12: C the Mighty if Command Enter your favorite number:

Type your favorite number. Mine is 11. Press Enter. If I type 72 (my height), 18, and 11, for example, I see the following result, due April 15: You owe $7920 in taxes.

Sheesh! And I thought the old system was bad. I guess I need a smaller favorite number. The second if comparison is “greater than or equal to.” This catches the case when your height is equal to the temperature. If both values are equal, the values of both the tax1 and tax2 variables are equal. The first if comparison, “tax1 is greater than tax2,” fails because both are equal. The second comparison, “tax1 is greater than or equal to tax2,” passes when tax1 is greater than tax2 or when both values are equal. If you enter zero as your favorite number, the program doesn’t say that you owe any tax. Unfortunately, the IRS does not allow you to have zero — or any negative numbers — as your favorite number. Sad, but true.

If It Isn’t True, What Else?

Hold on to that tax problem! No, not the one the government created. Instead, hold on to the TAXES.C source code introduced in the preceding section. If it’s already in your text editor, great. Otherwise, open it in your editor for editing. The last part of the TAXES.C program consists of two if statements. The second if statement, which should be near Line 23 in your editor, really isn’t necessary. Rather than use if in that manner, you can take advantage of another word in the C language, else. Change Line 23 in the TAXES.C program. 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. No comparison and no semicolon, and make sure that you type it in lowercase.

157

158

Part III: Giving Your Programs the Ability to Run Amok Save the file back to disk. Compile TAXES.C. Run the final result. 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). What you have done is to create an if-else structure, which is another way to handle the decisionmaking process in your C programs. The else keyword is a second, optional part of an if cluster of state­ ments. It groups together statements that are to be executed when the condition that if tests for isn’t true. Or else what? Alas, if you enter the same values as in the old program, you still owe the same bundle to Uncle Sam.

Covering all the possibilities with else

The if-else keyword combination allows you to write a program that can make either-or decisions. By itself, the if keyword can handle minor deci­ sions and execute special instructions if the conditions are just so. But when if is coupled with else, your program takes one of two directions, depend­ ing on the comparison if makes. Figure 12-2 illustrates how this can happen.

Chapter 12: C the Mighty if Command If the comparison is true, the statements belonging to the if statement are executed. But, if the comparison is false, the statements belonging to the else are executed. The program goes one way or the other, as illustrated in Figure 12-2. 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 if format with else

The else keyword is used in an if statement. The keyword holds its own group of statements to be executed (okay, “obeyed”) when the if compari­ son isn’t true. Here’s the format: if(comparison) { statement(s); } else { statement(s); }

The if keyword tests the comparison in parentheses. If it’s a true comparison — no foolin’ — the statements that appear in curly braces right after the if statement are executed. But, if the comparison is false, those statements following the else keyword and enclosed in curly braces are executed. One way or another, one group of statements is executed and the other isn’t. The else keyword, like all words in the C language, is in lowercase. It isn’t followed by a semicolon. Instead, a set of curly braces follows the else. The curly braces enclose one or more statements to be run when the comparison that if makes isn’t true. Notice that those statements each must end in a semicolon, obeying the laws of C first etched in stone by the ancient Palo Altoites. The statements belonging to the else keyword are executed when the condi­ tion that the if keyword evaluates is false. Table 12-2 illustrates how it works, showing you the opposite conditions for the comparisons that an if keyword would make.