- •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
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:
Chapter 11: C More Math and the Sacred Order of Precedence 139
#include <stdio.h> #include <stdlib.h>
int main()
{
char weight[4]; int w;
printf(“Enter your weight:”); gets(weight); w=atoi(weight);
printf(“Here is what you weigh now: %d\n”,w); w=w+1;
printf(“Your weight after the potatoes: %d\n”,w); w=w+1;
printf(“Here you are after the mutton: %d\n”,w); w=w+8;
printf(“And your weight after dessert: %d pounds!\n”,w); printf(“Lardo!\n”);
return(0);
}
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.
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 <stdio.h> #include <stdlib.h>
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.