- •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
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.
Program execution
printf("whatever");
?if(chins>3)
True {
printf("Where is your neck?");
|
} |
|
else |
False |
{ |
printf("My, but what a slender neck.");
|
} |
Figure 12-2: |
printf("something else"); |
|
How if and else affect a program.
Chapter 12: C the Mighty if Command 159
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.
160 Part III: Giving Your Programs the Ability to Run Amok
Table 12-2 |
if Comparisons and Their Opposites |
|
if Comparison |
else Statement Executed By This Condition |
|
< |
>= |
(Greater than or equal to) |
|
|
|
== |
!= |
(Not equal to) |
|
|
|
> |
<= |
(Less than or equal to) |
|
|
|
<= |
> |
(Greater than) |
|
|
|
>= |
< |
(Less than) |
|
|
|
!= |
== |
(Is equal to) |
|
|
|
I don’t know about you, but I think that all those symbols in Table 12-2 would certainly make an interesting rug pattern.
The else keyword is used only with if.
Both if and else can have more than one statement enclosed in their curly braces. if’s statements are executed when the comparison is true; else’s statements are executed when the comparison is false.
To execute means to run. C programs execute, or run, statements from
the top of the source code (the first line) to the bottom. Each line is executed one after the other unless statements like if and else are encountered. In that case, the program executes different statements, depending on the comparison that if makes.
When your program doesn’t require an either-or decision, you don’t have to use else. For example, the TAXES program has an either-or deci sion. But, suppose that you’re writing a program that displays an error message when something doesn’t work. In that case, you don’t need else; if an error doesn’t occur, the program should continue as normal.
If you’re the speaker of another programming tongue, notice that the C
language has no end-else word in it. This isn’t smelly old Pascal, for goodness’ sake. The final curly brace signals the end of the else state ment, just as it does with if.
The strange case of else-if and even more decisions
The C language is rich with decision making. The if keyword helps if you need to test for only one condition. True or false, if handles it. And, if it’s true, a group of statements is executed. Otherwise, it’s skipped over. (After the if’s group of statements is executed, the program continues as before.)
Chapter 12: C the Mighty if Command 161
Silly formatting trivia
The if-else structure need not be heavyladen with curly braces. Just as you can abbre viate an if statement to one line, you can also abbreviate else. I don’t recommend it, which is why I’m terribly brief and don’t ever show a program that illustrates examples this crudely:
if(tax1>tax2)
{
printf(“You owe $%i in taxes.\n”,tax1*10);
}
else
{
printf(“You owe $%i in taxes.\n”,tax2*10);
}
In this example, you see the meat and potatoes of the TAXES.C program: the if-else struc ture. Because both if and else have only one statement belonging to them, you can abbrevi ate the source code this way:
if(tax1>tax2)
printf(“You owe $%i in taxes.\n”,tax1*10);
else
printf(“You owe $%i in taxes.\n”,tax2*10);
This format keeps the indenting intact, which is one way to see what belongs to what (and also to easily identify the if-else structure). The following format is also possible, though it makes the program hard to read:
if(tax1>tax2) printf(“You owe $%i in taxes.\n”,tax1*10);
else printf(“You owe $%i in taxes.\n”,tax2*10);
Everything is scrunched up on two lines; the if statement has its own line, and the else has its own line. Both lines end with a semicolon, which is how this works as two statements in the C language. But, look-it. It’s gross! Please don’t write your programs this way.
You can do this trick — eliminating the curly braces — whenever only one statement appears with an if or else keyword. If multi ple statements must be executed, you’re required by law to use the curly braces. That’s why I recommend them all the time: No sense risking prison over brevity. To wit:
if(tax1>tax2)
printf(“You owe $%i in taxes.\n”,tax1*10);
else
{
printf(“You owe $%i in taxes.\n”,tax2*10); printf(“It pays to live where it’s cold!\n”);
}
Because two printf statements belong to the preceding else, the curly braces are required.
Either-or conditions are the daily bread of the if-else duo. Either way, one set of statements is executed and not the other, depending on the compari son made by if.
What about “one, two, or the third” types of decisions? For them, you need the miraculous and overly versatile else-if combination. It really drives you batty, but it’s handy.
162 Part III: Giving Your Programs the Ability to Run Amok
The following program is a modification of the GENIE1.C source code, as shown earlier in this chapter. This time, the else-if combination is used to allow the computer genie to accurately report whether the number is less than 5, equal to 5, or greater than 5:
#include <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”);
}
else if(number==5)
{
printf(“You typed in 5!\n”);
}
else
{
printf(“That number is more than 5!\n”);
}
printf(“The genie knows all, sees all!\n”); return(0);
}
Start working on this source code by loading the GENIE1.C source code I show you how to create earlier in this chapter. Make modifications so that the latter part of the program looks like the new, GENIE2.C source code that was just listed.
Watch your indenting. Pay attention to everything; two equal signs are in the else-if comparison. Pay attention to where semicolons go and where they don’t go.
After inserting the new lines, save the file to disk as GENIE2.C.
Compile GENIE2.C. If the error monster rears its ugly head, reedit the source code and then recompile.