- •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 7
A + B = C
In This Chapter
Changing a variable’s value
Introducing the int
Converting text with the atoi() function
Using +, -, *, and /
Struggling with basic math
It’s time to confirm your worst fears. Yes, computers have something to do with math. But it’s more of a passing fancy than the infatuation you’re now dreading. Unless you’re some hard-core type of engineer (the enginerd), math ematics plays only a casual role in your programs. You add, subtract, divide,
multiply, and maybe do a few other things. Nothing gets beyond the skills of anyone who can handle a calculator. It’s really fourth-grade stuff, but because we work with variables— which is more like eighth-grade algebra stuff — this material may require a little squeezing of the brain juices. In this chapter, I try to make it as enjoyable as possible for you.
The Ever-Changing Variable
A variable is a storage place. The C compiler creates the storage place and sets aside room for you to store strings of text or values — depending on the type of storage place you create. You do this by using a smattering of C lan guage keywords that you soon become intimate with.
What’s in the storage place? Could be anything. That’s why it’s called a vari able. Its contents may depend on what’s typed at the keyboard, the result of some mathematical operation, a campaign promise, or a psychic prediction. The contents can change too — just like the psychic prediction or campaign promise.
76 |
Part II: Run and Scream from Variables and Math |
It’s by juggling these variables that work gets done in most programs. When you play PacMan, for example, his position on the screen is kept in a vari able because, after all, he moves (his position changes). The number of points PacMan racks up are stored in a variable. And, when you win the game, you enter your name, and that too is stored in a variable. The value of these items — PacMan’s location, your points, your name — are changing or can change, which is why they’re stored in variables.
Variables are information-storage places in a program. They can con tain numbers, strings of text, and other items too complex to get into right now.
The contents of a variable? It depends. Variables are defined as being able to store strings of text or numbers. Their contents depend on what happens when the program runs, what the user types, or the computer’s mood, for example. Variables can change.
Where are variables stored? In your computer’s memory. This informa tion isn’t important right now; the computer makes room for them as long as you follow proper variable-creating procedures in your C programs.
Strings change
The following program is brought to you by the keyword char and by the printf() and gets() functions. In this program, a string variable, kitty, is created, and it’s used twice as the user decides what to name her cat. The changing contents of kitty show you the gist of what a variable is:
#include <stdio.h>
int main()
{
char kitty[20];
printf(“What would you like to name your cat?”);
gets(kitty);
printf(“%s is a nice name. What else do you have in mind?”,kitty);
gets(kitty);
printf(“%s is nice, too.\n”,kitty); return(0);
}
Enter the source code for KITTY.C into your text editor. Save the file to disk as KITTY.C.
Chapter 7: A + B = C 77
Compile KITTY.C. If you get any errors, reedit your source code. Check for missing semicolons, misplaced commas, and so on. Then recompile.
Running the program is covered in the next section.
The char keyword is used to create the variable and set aside storage for it.
Only by assigning text to the variable can its contents be read.
It’s the gets() function that reads text from the keyboard and sticks it into the string variable.
Running the KITTY
After compiling the source code for KITTY.C in the preceding section, run the final program. The output looks something like this:
What would you like to name your cat?Rufus
Rufus is a nice name. What else do you have in mind?Fuzzball
Fuzzball is nice, too.
The kitty variable is assigned one value by using the first gets() function. Then, it’s assigned a new value by the second gets() function. Though the same variable is used, its value changes. That is the idea behind variables.
A single variable can be used many times in a program. It can be used over and over with the same value, or used over and over to store differ ent values.
It’s the contents of the string variable that are displayed — not the vari able name. In the KITTY.C program, the variable is named kitty. That’s for your reference as a programmer. What’s stored in the variable is what’s important.
Welcome to the Cold World of
Numeric Variables
Just as strings of text are stored in string variables, numbers are stored in numeric variables. This allows you to work with values in your program and to do the ever-dreaded math.
78 |
Part II: Run and Scream from Variables and Math |
To create a numeric variable and set aside storage space for a number, a spe cial C language keyword is used. Unlike char, which creates all types of strings, different keywords are used to create variables for storing different types of numbers. It all depends on how big or how weird the number is.
Hello, integer
To keep things sane for now, I show you only one of the numeric variable types. It’s the simplest form of a number, the integer. Just say “IN-tuh-jur.” Integer.
Here’s how the typical C compiler defines an integer type of number:
An integer is a whole number — no fractions, decimal parts, or funny stuff.
An integer can have a value that ranges from 0 to 32,767.
Negative numbers, from –32,768 up to 0 are also allowed.
Any other values — larger or smaller, fractions, or values with a decimal point, such as 1.5 — are not integers. (The C language can deal with such numbers, but I don’t introduce those types of variables now.)
To use an integer variable in a program, you have to set aside space for it. You do this with the int keyword at the beginning of the program. Here’s the format:
int var;
The keyword int is followed by a space (or a press of the Tab key) and then the name of the variable, var. It’s a complete statement in the C language, and it ends with a semicolon.
Some compilers may define the range for an int to be much larger than –32,768 through 32,767. To be certain, check with your compiler’s docu mentation or help system.
On older, 16-bit computers, an integer ranges in value from –32,768 through 32,767.
On most modern computers, integer values range from –2,147,483,647 through 2,147,483,647.
More information about naming a variable — and other C language trivia about variables — is offered in Chapter 8. For now, forgive me for the unofficial introduction.