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