- •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 13: What If C==C? 171
The fpurge() function specifically erases text waiting to be read. I have noticed that it’s required for Unix, Linux, and Mac OS programs.
“Can I get getchar() to read only one character?”
Alas, the getchar() function isn’t a keyboard-reading function per se. What it really does is read standard input, which for nearly all computers I have used is text typed at the keyboard.
To read the keyboard, you need a specific function. Some versions of GCC for Windows use the getch() and getche() functions, which can read text directly from the keyboard and lack the standard input problems of getchar(). The problem with illustrating these functions in this book is that they don’t have a Unix counterpart.
To read the keyboard directly in Unix, you have to access the terminal being used and then interpret which keyboard codes are being generated. Another solution is to use the Curses programming library.
Alas, this book doesn’t have room to describe all these keyboard-reading func tions. Instead, I recommend that you pick up this book’s companion, C All-in- One Desk Reference For Dummies (Wiley).
Meanwhile, back to the GREATER problem
Now that you may have ironed out the problem with getchar() in the GREATER program, it’s time to examine the output. Run the program again, just for old time’s sake. Try to see whether the ‘–’ character is greater than the ‘$’.
Which character is greater?
Type a single character:-
Type another character:$ ‘-’ is greater than ‘$’!
And, why is that?
You see, the if command doesn’t know squat about letters, numbers, or symbols. Rather than compare the character’s physique, if compares the character’s corresponding ASCII code values.
172 Part III: Giving Your Programs the Ability to Run Amok
The ASCII code value for the minus sign is 45. The code value for the dollar sign is 36. Because 36 is less than 45, the computer thinks that the ‘–’ is greater than the ‘$’. This also holds true for letters of the alphabet and their ASCII code values.
In real life, rarely do you compare one letter to another. Instead, you compare whatever keystroke was entered with a known, desired choice. I cover this topic in the next section.
See Appendix B for a gander at ASCII values.
Run the program again and try typing these two letters: a (little a) and Z. The big Z is less than the little A, even though A comes before Z in the alphabet. The reason is that the ASCII code has two alphabets: one for uppercase letters and another for lowercase. The uppercase letters have smaller values than the lowercase letters do, so “a-z” always is greater than “A-Z”.
Severely boring trivia on the nature of “alphabetical order”
So why is it A, B, C first, and why does Z come last? The answer is buried in the bosom of trivia, which most computer junkies are also fond of memorizing. Because I was curious, I thought I would look it up. And, lo, here’s what I found.
Our alphabet is based on ancient alphabets, which in turn are based on even older, dinosaurage alphabets. Back in those days, the letters they used were based on symbols for various things they encountered in everyday life, and the symbols were often named after those things as well: The letter A was named after and shaped like the ox, an important beast. B was named after a house and shaped like a door. And so on for all the letters. That’s how it was for most of the early Semitic languages, which used phon ics rather than pictographs or ideographs.
The Greeks borrowed their alphabet from the Semites. The Romans stole their alphabet from
the Greeks (the Romans stole just about every thing). But the Romans didn’t really steal all of Greek. They left out a few sounds they didn’t think they needed: (theta), U, V, X, Y, and Z. Eventually, they realized that the sounds were important, so they added them to the end of their alphabet in the order in which they were accepted. (The theta was never added by the Romans, though some middle English scripts used a Y symbol to represent it. That’s why, for example, you have “Ye Old Shop” for “The Old Shop.”)
That sort of explains how the alphabet got to be in alphabetical order. The ASCII numbering scheme came about from the early teletype days as a way to encode numbers, common symbols, and secret codes. There’s probably a story to tell there, but at this stage in the book, I’m just too lazy to look it up.
Chapter 13: What If C==C? 173
Another, bolder example
About the most common use of the if command to compare characters is in answer to the old yes-or-no question. Here’s an example:
#include <stdio.h>
int main()
{
char c;
printf(“Would you like your computer to explode?”); c=getchar();
if(c==’N’)
{
printf(“Okay. Whew!\n”);
}
else
{
printf(“OK: Configuring computer to explode now.\n”); printf(“Bye!\n”);
}
return(0);
}
Oh! Such jocularity!
Enter the preceding source code. Save it to disk as BLOWUP1.C.
Compile and run. Here’s what you see:
Would you like your computer to explode?
Thanks to your years of computer training, you know that the answer is No. What can the user type? Who cares! As the programmer you know that you type a big N to make the computer not explode. Any other key makes it go Boom. Type N and press Enter:
Okay. Whew!
Run the program again and type any other key except N. (Even little N works.) Boom! There goes the computer!
Only if the user types a capital N does the computer not explode.
Well, the computer doesn’t explode, which you should have figured out by now.
174 Part III: Giving Your Programs the Ability to Run Amok
Even to compare a single character variable with a single character, two equal signs are used.
Yes, this program has its limitations. Most of them are covered in Chapter 14.
Using the if Keyword to
Compare Two Strings
The if keyword cannot be used to compare strings. It can be used only to compare single-character variables.
If you try to use if to compare two strings, the result is, as they say, unpredictable. The program is compiled without any errors (maybe), but it definitely doesn’t run the way you anticipated.
C All-in-One Desk Reference For Dummies (Wiley) has information about comparing strings.