- •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 79
Yes! You’re very observant. This type of int is the same one used to declare the main() function in every program you have written in this book — if you have been reading the chapters in order. Without getting too far ahead, you should now recognize that main() is known as an “integer function.” It also ties into the 0 value in the return statement, but I tell you more about that in a few chapters.
Computer geeks worldwide want you to know that an integer ranges from –32,768 up to 0 and then up to 32,767 only on personal computers. If, per chance, you ever program on a large, antique computer — doomed to ever-dwindling possibilities of employment, like those losers who pro gram them — you may discover that the range for integers on those computers is somewhat different. Yeah, this information is completely optional; no need cluttering your head with it. But they would whine if I didn’t put it in here.
Using an integer variable in the Methuselah program
If you need only small, whole-number values in a C program, you should use integer variables. As an example, the following program uses the variable age to keep track of someone’s age. Other examples of using integer variables are to store the number of times something happens (as long as it doesn’t happen more than 32,000-odd times), planets in the solar system (still 9), corrupt congressmen (always less than 524), and number of people who have seen Lenin in person (getting smaller every day). Think “whole numbers, not big.”
The following program displays the age of the Biblical patriarch Methuselah, an ancestor of Noah, who supposedly lived to be 969 years old — well beyond geezerhood. The program is METHUS1.C, from Methus, which was his nickname:
#include <stdio.h>
int main()
{
int age;
age=969;
printf(“Methuselah was %d years old.\n”,age); return(0);
}
Enter the text from METHUS1.C into your editor. Save the file to disk as METHUS1.C.
80 |
Part II: Run and Scream from Variables and Math |
Compile the program. If you get any errors, reedit the source code and make sure that everything matches the preceding listing. Recompile.
Run the program and you see the following:
Methuselah was 969 years old.
The variable age was assigned the value 969. Then, the printf() statement was used, along with the %d placeholder, to display that value in a string.
The fifth line creates the age variable, used to store an integer value.
The seventh line assigns the value 969 to the age variable by using the equal sign (=). The variable age comes first, and then the equal sign, and then the value (969) to be placed in the age variable.
In the eighth line, the printf function is used to display the value of the age variable. In printf()’s formatting string, the %d conversion charac ter is used as a placeholder for an integer value. %d works for integers, just as %s is a placeholder for a string.
Assigning values to numeric variables
One thing worth noting in the METHUS1 program is that numeric variables are assigned values by using the equal sign (=). The variable goes on the left, and then the equal sign, and then the “thing” that produces the value on the right. That’s the way it is, was, and shall be in the C language:
var=value;
var is the name of the numeric variable. value is the value assigned to that variable. Read it as “The value of the variable var is equal to the value value.” (I know, too many values in that sentence. So shoot me.)
What could value be? It can be a number, a mathematical equation, a C lan guage function that generates a value, or another variable, in which case var has that variable’s same value. Anything that pops out a value — an integer value, in this case — is acceptable.
In METHUS1.C, the value for the variable age is assigned directly:
age=969;
Lo, the value 969 is safely stuffed into the age variable.
Chapter 7: A + B = C 81
The equal sign is used to assign a non-string value to a variable. The variable goes on the left side of the equal sign and gets its value from whatever’s on the right side.
String variables cannot be defined in this way, by using an equal sign. You cannot say
kitty=”Koshka”;
It just doesn’t work! Strings can be read into variables from the keyboard by using the scanf(), gets(), or other C language keyboard-reading functions. String variables can also be preset, but you cannot use an equal sign with them, like you can with numeric variables!
Entering numeric values from the keyboard
Keep the METHUS1.C program warm in your editor’s oven for a few seconds. What does it really do? Nothing. Because the value 969 is already in the pro gram, there’s no surprise. The real fun with numbers comes when they’re entered from the keyboard. Who knows what wacky value the user may enter? (That’s another reason for a variable.)
A small problem arises in reading a value from the keyboard: Only strings are read from the keyboard; the scanf() and gets() functions you’re familiar with have been used to read string variables. And, there’s most definitely a dif ference between the characters “969” and the number 969. One is a value, and the other is a string. (I leave it up to you to figure out which is which.) The object is to covertly transform the string “969” into a value — nay, an integer value — of 969. The secret command to do it is atoi, the A-to-I function.
The atoi() function
The atoi() (pronounced “A-to-I”) function converts numbers at the begin ning of a string into an integer value. The A comes from the acronym ASCII, which is a coding scheme that assigns secret code numbers to characters. So atoi means “convert an ASCII (text) string into an integer value.” That’s how you can read integers from the keyboard. Here’s the format:
var=atoi(string);
var is the name of a numeric variable, an integer variable created by the int keyword. That’s followed by an equal sign, which is how you assign a value to a variable.
82 |
Part II: Run and Scream from Variables and Math |
On the difference between numbers and strings, if you dare to care
You have to know when a number in C is a value and when it’s a string. A numeric value is what you find lurking in a numeric variable. This book calls those things values, and not numbers. A value is 5 apples, 3.141 (for example), the national debt, and the number of pounds you can lose on celebrity diets featured in this week’s Star. Those are values.
Numbers are what appear in strings of text. When you type 255, for example, you’re enter ing a string. Those are the characters 2, 5, and 5, as found on your keyboard. The string “255” is not a value. I call it a number. By using the
atoi() function in the C language, you can translate it into a value, suitable for storage in a numeric variable.
There are numbers and there are values. Which is which? It depends on how you’re going to use it. Obviously, if someone is entering a phone number, house number, or zip code, it’s probably a string. (My zip code is 94402, but that doesn’t mean that it’s the 94-thousandth-something post office in the United States.) If some one enters a dollar amount, percentage, size, or measurement — anything you work with mathematically — it’s probably a value.
The atoi() function follows the equal sign. Then comes the string to con vert, hugged by atoi()’s parentheses. The string can be a string variable or a string “constant” enclosed in double quotes. Most often, the string to convert is the name of a string variable, one created by the char keyword and read from the keyboard by using gets() or scanf() or some other keyboardreading function.
The line ends in a semicolon because it’s a complete C language statement.
The atoi function also requires a second number-sign thingy at the begin ning of your source code:
#include <stdlib.h>
This line is usually placed below the traditional #include <stdio.h> thing — both of them look the same, in fact, but it’s stdlib.h in the angle pinchers that’s required here. The line does not end with a semicolon.
atoi is not pronounced “a toy.” It’s “A-to-I,” like what you see on the spine of Volume One of a 3-volume encyclopedia.
Numbers are values; strings are composed of characters.
If the string that atoi() converts does not begin with a number, or if the number is too large or too weird to be an integer, atoi spits back the value 0 (zero).