- •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
150 Part III: Giving Your Programs the Ability to Run Amok
The #include <stdlib.h> part is necessary because the program uses the atoi() function.
The if command is followed by parentheses, which contain the compar ison that the if keyword tests.
The comparison that if makes tests the value of the variable number with 5. The < symbol between them means “less than.” The test reads “If the value of the variable number is less than 5.” If this is true, the cluster of statements following the if keyword is executed. If the test proves false, the cluster of statements is skipped.
Remember the < — less than — from school? Good!
Notice that the if test isn’t followed by a semicolon! Instead, it’s fol lowed by a statement enclosed in curly braces. The statements (there can be more than one) “belong” to the if command and are executed only if the condition is true.
If you see only the line The genie knows all, sees all!, you proba bly typed a number greater than 4 (which includes 5 and higher). The reason is that the if statement tests only for values less than 5. If the value is less than 5, That number is less than 5! is displayed. The next section elaborates on how it all works.
No, the computer genie doesn’t know all and see all if you type a number 5 or greater.
Did you notice the extra set of curly braces in the middle of this pro gram? That’s part of how the if statement works. Also notice how they’re indented.
The if keyword, up close and impersonal
It’s unlike any other C language word you have seen. The if keyword has a unique format, with plenty of options and room for goofing things up. Yet, it’s a handy and powerful thing that you can put in your programs — something you use a lot.
The if keyword is used to make decisions in your programs. It makes a com parison. If the result is true, the rest of the if statement is executed. If the comparison isn’t true, the program skips over the rest of the if statement, as shown in Figure 12-1.
The if statement is a statement “block” that can look like this:
if(comparison)
{
statement; [statement;...]
}
Chapter 12: C the Mighty if Command 151
Program execution
|
? |
printf("whatever"); |
|
if(chins>3) |
|
False |
True |
{ |
|
|
printf("Where is your neck?"); |
|
|
} |
Figure 12-1: |
|
printf("something else"); |
How if |
|
|
affects a |
|
|
program. |
|
|
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 |
|
< |
Less than |
1 |
< 5 |
|
|
|
|
|
|
8 |
< 9 |
|
|
|
|
== |
Equal to |
5 |
== 5 |
|
|
|
|
|
|
0 |
== 0 |
|
|
|
|
(continued)
152 Part III: Giving Your Programs the Ability to Run Amok
Table 12-1 (continued)
Comparison |
Meaning or Pronunciation |
“True” Examples |
|
> |
Greater than |
8 |
> 5 |
|
|
|
|
|
|
10 > 0 |
|
|
|
|
|
<= |
Less than or equal to |
4 |
<= 5 |
|
|
|
|
|
|
8 |
<= 8 |
|
|
|
|
>= |
Greater than or equal to |
9 |
>= 5 |
|
|
|
|
|
|
2 |
>= 2 |
|
|
|
|
!= |
Not equal to |
1 |
!= 0 |
|
|
|
|
|
|
4 |
!= 3.99 |
|
|
|
|
The GENIE1 program, from the preceding section, uses this if statement:
if(number<5)
{
printf(“That number is less than 5!\n”);
}
The first line is the if keyword and its comparison in parentheses. What’s being compared is the value of the numeric variable number and the constant value 5. The comparison is “less than.” Is number less than 5? If so, the state ment in curly braces is executed. If not, the whole deal is skipped over.
Consider these modifications:
if(number==5)
{
printf(“That number is 5!\n”);
}
Now, the comparison is number==5? (Is the number that is entered equal to five?) If it is, the printf() statement displays That number is 5!
These changes compare the value of number with 5 again:
if(number>=5)
{
printf(“That number is more than 4!\n”);
}
Chapter 12: C the Mighty if Command 153
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<5)
{
printf(“That number is less than 5!\n”); printf(“By goodness, aren’t I smart?\n”);
}
Everything between the curly braces is executed when the comparison is true. Advanced C programs may have lots of stuff in there; as long as it’s between the curly braces, it’s executed only if the comparison is true. (That’s why it’s indented — so that you know that it all belongs to the if statement.)
The comparison that if makes is usually between a variable and a value. It can be a numeric or single-character variable.
if cannot compare strings. For information on comparing strings, refer to my book C All-in-One Desk Reference For Dummies (Wiley).
Less than and greater than and their ilk should be familiar to you from basic math. If not, you should know that you read the symbols from left to right: The > 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: <= and >=. 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.