- •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 83
The purpose of #include <stdlib.h> is to tell the compiler about the atoi() function. Without that line, you may see some warning or “no prototype” errors, which typically ruin your programming day.
STDLIB.H is the standard library header file, don’t you know.
Other C language functions are available for converting strings into noninteger numbers. That’s how you translate input from the keyboard into a numeric value: You must squeeze a string by using a special function (atoi) and extract a number.
So how old is this Methuselah guy, anyway?
The following program is METHUS2.C, a gradual, creeping improvement over METHUS1.C. In this version of the program, you read a string that the user types at the keyboard. That string — and it is a string, by the way — is then magically converted into a numeric value by the atoi() function. Then, that value is displayed by using the printf() function. A miracle is happening here, something that the ancients would be truly dazzled by, probably to the point of offering you food and tossing fragrant posies your way.
#include <stdio.h> #include <stdlib.h>
int main()
{
int age;
char years[8];
printf(“How old was Methuselah?”); gets(years);
age=atoi(years);
printf(“Methuselah was %d years old.\n”,age); return(0);
}
Hunt and peck the METHUS2.C source code into your editor. You can edit the original METHUS1.C source code, but be careful to save it to disk under the new name, METHUS2.C.
Compile the program. Repair any errors you may have encountered.
Run the program. The output you see may look something like this:
How old was Methuselah?26
Methuselah was 26 years old.
84 |
Part II: Run and Scream from Variables and Math |
No, you don’t have to experiment with METHUS2.C, but I encourage you to try this
Thank goodness this book isn’t Surgery For Dummies. Unlike that sober tome, this book allows you to freely fiddle, poke, pull, experi ment, and have fun. Trying that with a cadaver is okay, but in Chapter 14 of Surgery For Dummies, “Finding That Pesky Appendix on Your Nephew,” it’s frowned on.
Run the METHUS2.C program again, and when the program asks you for Methuselah’s age, type the following value:
10000000000
That’s ten billion — a one with 10 zeroes and no commas. Press Enter and the output tells you that the old guy was 1,410,065,408 years old — or some other value, not what you typed. The reason is that you entered a value greater than an integer can hold. The value returned is the remainder of what you entered divided by the maximum size of an integer in your compiler.
How about typing the following value:
-64
Yes, Mr. M. could never be negative 64 years old, but the program accepts it. The reason is that integer values include negative numbers.
Here’s one you need to try:
4.5
Is the oldest human really four-and-a-half? Probably at one time. Still, the program insists that he was only four. That’s because the point 5 part is a fraction. Integers don’t include frac tions, so all the atoi() function reads is the 4.
Finally, the big experiment. Type the following as Methus’s age:
old
Yes, he was old. But when you enter old into the program, it claims that he was only zero. The reason is that the atoi() function didn’t see a number in your response. Therefore, it gener ates a value of zero.
In this example, the user typed 26 for the age. That was entered as a string, transformed by atoi() into an integer value and, finally, displayed by printf(). That’s how you can read in numbers from the keyboard and then fling them about in your program as numeric values. Other sections in this chapter, as well as in the rest of this book, continue to drive home this message.
Okay, legend has it that the old man was 969 when he finally (and prob ably happily) entered into the hereafter. But by using this program, you can really twist history (though Methuselah probably had lots of con temporaries who lived as long as you and I do).
If you forget the #include <stdlib.h> thing or you misspell it, a few errors may spew forth from your compiler. Normally, these errors are tame “warnings,” and the program works just the same. Regardless, get
Chapter 7: A + B = C 85
in the habit of including the stdlib thing when you use the atoi() function.
The age=atoi(years) function is how the string years is translated into a numeric value. The atoi() function examines the string and spits up a number. That number is then placed in the age variable as a numeric value.
Why not just print the string years? Well, you can. By replacing age with years and %d with %s in the final printf() function, the program dis plays the same message. To wit:
printf(“Methuselah was %s years old.\n”,years);
The output is the same. However, only with a numeric variable can you perform mathematical operations. Strings and math? Give up now and keep your sanity!
You and Mr. Wrinkles
Time to modify the old Methuselah program again. This time, you create the METHUS3.C source code, as shown next. As with METHUS2.C, only subtle modifications are made to the original program. Nothing new, though you’re building up to something later in this chapter.
#include <stdio.h> #include <stdlib.h>
int main()
{
int methus; int you;
char years[8];
printf(“How old are you?”); gets(years); you=atoi(years);
printf(“How old was Methuselah?”); gets(years);
methus=atoi(years);
printf(“You are %d years old.\n”,you); printf(“Methuselah was %d years old.\n”,methus); return(0);
}
Double-check your source code carefully and save the file to disk as METHUS3.C.
86 |
Part II: Run and Scream from Variables and Math |
Compile METHUS3.C. Fix any errors that sneak into the picture.
Run the program. You’re asked two questions, and then two strings of text are displayed — something like the following:
How old are you?29
How old was Methuselah?969
You are 29 years old.
Methuselah was 969 years old.
Of course, this data is merely regurgitated. The true power of the computer is that math can be done on the values — and it’s the computer that does the math, not you. Don’t sweat it!
You’re not really 29.
Yes, the years string variable is used twice. First, it reads in your age, and then the atoi() function converts it and saves the value in the you variable. Then, years is used again for input. This strategy works because the original value was saved in another variable — a cool trick.
The METHUS3.C program has been divided into four sections. This is more of a visual organization than anything particular to the C program ming language. The idea is to write the program in paragraphs — or thoughts — similar to the way most people try to write English.
A Wee Bit o’ Math
Now is the time for all good programmers to do some math. No, wait! Please don’t leave. It’s cinchy stuff. The first real math explanation is several pages away.
When you do math in the C programming language, it helps to know two things: First, know which symbols — or, to be technical, unique doodads — are used to add, subtract, multiply, and divide numbers. Second, you have to know what to do with the results. Of course, you never have to do the math. That’s what the computer is for.
Basic mathematical symbols
The basic mathematical symbols are probably familiar to you already if you have been around computers a while. Here they are:
Chapter 7: A + B = C 87
Addition symbol: +
Subtraction symbol: –
Multiplication symbol: *
Division symbol: /
Incidentally, the official C language term for these dingbats is operators. These are mathematical (or arithmetic — I never know which to use) operators.
+ Addition: The addition operator is the plus sign, +. This sign is so basic that I can’t really think of anything else you would use to add two numbers:
var=value1+value2;
Here, the result of adding value1 to value2 is calculated by the computer and stored in the numeric variable var.
– Subtraction: The subtraction operator is the minus sign, –:
var=value1-value2;
Here, the result of subtracting value2 from value1 is calculated and gently stuffed into the numeric variable var.
* Multiplication: Here’s where we get weird. The multiplication operator is the asterisk — not the × character:
var=value1*value2;
In this line, the result of multiplying value1 by value2 is figured out by the computer, and the result is stored in the variable var.
/ Division: For division, the slash, /, is used; the primary reason is that the ÷ symbol is not on your keyboard:
var=value1/value2;
Here, the result of dividing value1 by value2 is calculated by the computer and stored in the variable var.
Note that in all cases, the mathematical operation is on the right side of the equal sign — something like this:
value1+value2=var;