- •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++
In This Chapter
Incrementing variables with ++
Decrementing variables with --
Using other math operator shortcuts
Looping is a core part of programming, just as compromising your princi ples is central to getting ahead in politics. And, closely tied to looping is
a concept you have already been exposed to: incrementation, which I’m not certain is a real word, but it means to increment something.
Just as loops flip through various iterations, variables are incremented or decremented to help the computer keep track of things. In fact, the concepts of looping and incrementation are so closely linked that it was tough to write the preceding chapter about the for command while utterly avoiding the issue. The time has come for your full exposure to that ancient art and mysterious practice of incrementation.
The Art of Incrementation
When a for loop repeats something seven times, a variable somewhere gets incremented seven times. For example:
for(i=0;i<7;i=i+1)
This for statement sets up a loop that is repeated seven times, from i=0 and up by 1 seven times as long as the value of i is less than 7 (i<7).
If you find the concept of starting the loop at 0 strange, the following for state ment performs the same trick, working itself out, over and over, seven times:
for(i=1;i<=7;i=i+1)
202 Part III: Giving Your Programs the Ability to Run Amok
In this example, i increments from 1 up to 7. The C lords prefer to start loops with the counting variable at 0 because that’s where the computer itself starts counting internally. Either way, incrementing is central to the idea of looping.
Keep in mind that the for statement is merely a frame for a loop. It repeats a group of statements a given number of times. The for statement itself only controls the looping.
Cryptic C operator symbols, Volume I:
The inc operator (++)
The art of incrementation involves taking a variable and adding 1 to its value. So, no matter what the original value of the variable count, it’s 1 greater after this equation:
count=count+1;
Face it: This equation is an awkward thing to look at. Yet, no loop happens without it, which means that incrementing happens frequently in C programs. Even so, few C programmers use the preceding statement. Instead, they resort to a shortcut, the incrementation operator, which is two plus signs holding hands:
count++;
The incrementation operator, ++, works like other mathematical operators you may have seen in other horrid math chapters: the +, -, *, and / for addition, subtraction, multiplication, and division, respectively. The difference here is that ++ works without an equal sign. It just tells the compiler, “Yo! Add 1 to the value of this variable. Thank you. Thank you very much.” It’s quick and tidy, but a bit cryptic (which is why I didn’t throw it at you right away).
Yes, you can say “plus plus” in your head when you see ++ in a program.
Yes, that’s why C++ is called “See plus plus.” It’s also the punch line of the joke: C++ is “one more” than regular C.
You don’t need an equal sign when you use ++. Just stick it at the end of a variable and that variable is incremented by 1.
The equation i++ is the same as i=i+1.
Here we go:
var=3; |
/* the variable var equals three */ |
var++; |
/* Oops! var is incremented here */ |
|
/* From here on, var equals four */ |
Chapter 16: C the Loop, C the Loop++ 203
The ++ operator is used this way in a for statement:
for(i=0;i<7;i++)
This line means that variable i is incremented every iteration of the loop.
This area is where the C language begins to get truly cryptic. Given the separate pieces of a for loop, most knowledgeable humans can detect that i=1 means “i equals 1” and that i<7 means “i is less than 7,” and even that i=i+1 is “i equals i plus 1.” But toss i++ at them and they think “i plus plus? Weird.”
Another look at the LARDO.C program
Chapter 11 touches on the idea of incrementing a variable in a program. That program is LARDO.C, which I’m certain is near and dear to your heart and has impressed many a friend and family member. Unfortunately, now that you know the ++ thing, the program would really be an embarrassment if you showed it to a C guru. Seriously, all those gauche w=w+1 things need to be properly changed to w++ commands. Short. Sweet. Cryptic. It’s what computers are all about!
The following program is an update to the LARDO.C source code, which is probably still sitting on your hard drive somewhere. Load that old file into your editor and make the necessary changes so that the program looks like the source code listed here:
#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: %i\n”,w); w++;
printf(“Your weight after the potatoes: %i\n”,w); w++;
printf(“Here you are after the mutton: %i\n”,w); w=w+8;
printf(“And your weight after dessert: %i pounds!\n”,w); printf(“Lardo!\n”);
return(0);
}
204 Part III: Giving Your Programs the Ability to Run Amok
Edit your source code. The only changes are to Lines 14 and 16.
Save the file to disk again, using the same name, because this program is so much more superior to the original. Then compile.
Fix any errors if you got ’em. Otherwise, the program runs the same as it did before. The only true difference? You took advantage of the incrementation operator, ++, and earned the clever wink of sophisticated C language pro grammers worldwide.
Notice that the w=w+8 statement wasn’t modified. The reason is that the vari able w is increased by 8, not just by 1. Yes, I have a shortcut for that, but you aren’t exposed to it until the end of this chapter.
The Mysterious Practice
of Decrementation
Loops don’t necessarily have to go forward. They can also count down, which is definitely more dramatic and required in some occupations — such as launching spacecraft and many other common things you find yourself doing every day.
Consider OLLYOLLY.C, a program that counts backward. And, that’s about all it’s good for:
#include <stdio.h>
int main()
{
int count;
for(count=10;count>0;count=count-1) printf(“%d\n”,count);
printf(“Ready or not, here I come!\n”); return(0);
}
Start off your editor with a new slate and carefully type this source code. The only strange stuff you encounter is in the for loop’s parentheses, which may look a little funky — but it’s counting backward! Will the loop work? Will the computer explode? Is Jane really cheating on Ralph? How can this be happening?