- •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 16: C the Loop, C the Loop++ 209
for(count=10;count>0;count--)
Save the source code file back to disk and then recompile it.
The program runs the same, but your C programming buddies will nod their heads in amazement at your deft use of the decrementation operator.
More Incrementation Madness
Incrementation and looping go hand in hand like (this week’s) Hollywood’s hottest couple.
Looping is an important part of programming — doing things over and over, like a famous actor rehearses his lines. (Make that famous stage actor.) In C, that can be done only with the for loop if you increment (or decrement) a variable’s value.
Tied in with looping are the ++ and -- operators, which you can also use independently from looping to increase or decrease a variable’s value — like some actresses increase their bust size through various surgical techniques, and their age via bald-faced lying.
Given that, you should still keep in mind that incrementing and decrementing don’t have to be done one tick at a time. For example, the LARDO.C program boosts the w variable’s value by 8 by using the following statement in Line 18:
w=w+8;
The value of the variable w is increased by 8. The following statement decreases w by 3:
w=w-3;
This is still a form of incrementing and decrementing, though values larger than 1 are used. It’s perfectly legit. And — as a bonus — you can use these types of incrementing or decrementing in loops. An example is coming forthwith.
Although you can increment a variable by a value larger than 1, the ++ operator increases a variable’s value by only 1. The same holds true for --, which always decreases a variable’s value by 1.
Fortunately, the C language lacks a +++ or --- operator. Forget about it!
210 Part III: Giving Your Programs the Ability to Run Amok
Leaping loops!
After losing or wining the game, the kids get together as a team and chant:
2, 4, 6, 8, who do we appreciate?
This chant is followed by the other team’s name. It’s a nice, polite, all-American athletic chant that means either “You sad sacks were easy to beat and, if we were unsupervised, we would be vandalizing your bicycles by now” or “You defeated us through treachery and deceit and, if we were unsupervised, we would be pummeling your heads with our aluminum bats.”
Anyway, the following program uses a for loop to generate the “2, 4, 6, 8” part of the chant. It’s a for loop that, yes, skips a bit as it counts. It’s what I call a leaping loop:
#include <stdio.h>
int main()
{
int i;
for(i=2;i<10;i=i+2) printf(“%d “,i);
printf(“who do we appreciate? GNU!\n”); return(0);
}
Choose New in your editor and type the preceding source code. In the printf() statement in the for loop, note the space after the %d. It goes “double quote, percent sign, little d, space, double quote.” Save the file to disk as CHANT.C.
Compile and run the program. Here’s what your output should look like:
2 4 6 8 who do we appreciate? GNU!
The loop starts at 2 and increments up to 10 by using the i=i+2 formula. The loop reads like this: “Start with i equal to 2, and while the value of i is less than 10, repeat the following, adding 2 to variable i each time you loop.”
You can change Line 7 of the program to have the loop count by even numbers to any value. For example:
for(i=2;i<1000;i=i+2)
This modification makes the computer count by twos from 2 to 998. It doesn’t do much for the chant, but it works. (Indeed, it would take for ever to get to The Pizza Place if that were the case.)
Chapter 16: C the Loop, C the Loop++ 211
Counting to 1,000 by fives
The following program is an update to the old 100.C program, from Chapter 15. In this case, the program counts to 1,000 by fives — a task that would literally take days without a computer:
#include <stdio.h>
int main()
{
int i;
for(i=5;i<=1000;i=i+5)
printf(“%d\t”,i);
return(0);
}
Start off with a new, clean slate in your editor. Type the preceding source code. It’s nothing fancy. Indeed, it’s just a take-off from the old 100.C program. Save the file to disk as 1000.C.
Compile 1000.C and run the result. Your screen fills with values from 5 to 1000, all lined up in rows and columns.
This leaping loop counts by fives because of the i=i+5 part of the for statement. The i=i+5 operation keeps increasing the value of the i vari able by 5.
The loop begins counting at 5 because of the i=5 part of the for loop. It stops counting at 1,000 because of the i<=1000 part of the loop. That’s “less than or equal to 1000,” which is how you get to 1,000.
Cryptic C operator symbols, Volume III: The madness continues
C is full of shortcuts, and mathematical operations are where you find most of them clustered like bees over a stray Zagnut bar. I feel that the two most cryp tic shortcuts are for changing a variable’s value by 1: ++ to increment and -- to decrement. But there are more!
To add 5 to a variable’s value, for example, such as in the 1000.C program, you use the following:
i=i+5
212 Part III: Giving Your Programs the Ability to Run Amok
The cryptic C language shortcut for this operation is
i+=5
This line means “Increase the value of variable i by five.” Unfortunately, it just doesn’t look like that’s what it means.
Although I can swallow ++ to increment and -- to decrement, the += thing seri ously looks like a typo. Sad news: It’s not. Even sadder: There are more of them, one each for adding, subtracting, multiplying, or dividing a variable’s value by a certain amount (or by another variable). Table 16-2 lists the lot of them.
Table 16-2 |
Cryptic Shortcuts for Common Math Operations |
Long, Boring Way |
Cryptic Shortcut |
var=var+5 |
var+=5 |
|
|
x=x+y |
x+=y |
|
|
var=var-5 |
var-=5 |
|
|
x=x-y |
x-=y |
|
|
var=var*5 |
var*=5 |
|
|
x=x*y |
x*=y |
|
|
var=var/5 |
var/=5 |
|
|
x=x/y |
x/=y |
|
|
In Table 16-2, you see two examples for each cryptic shortcut. The first one uses the variable var, which is modified by a constant value, 5. The second uses two variables; the first one, x, is modified by another variable, y.
Yes, the shortcuts for incrementing, decrementing, or changing a variable are cryptic. You don’t have to use them. You suffer no penalty for forgetting about them. I refer to them here for two reasons: It can be done, and C gurus love tossing this stuff into programs; so don’t let the shortcuts scare you when you see them.
On your own: Modify the preceding two programs, CHANT.C and 1000.C.
Replace the long math condition in the for loop with a shortcut version.
Answers are provided at the end of this chapter.