- •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 25
Math Madness!
In This Chapter
Using more complex math functions
Understanding the pow() and sqrt() functions
Linking in the math library for Unix
Doing the post-/pre-increment/-decrement thing
Most people think that computer programming is all math. Boy, are they wrong. It involves math, to be sure, but the hard part — figuring out
the answer — is done by the computer. So, what’s the beef? Why run scream ing and hiding from this innocent, kind little chapter that merely discusses the various C language details, spells, and dance steps for juggling numbers?
More on Math
The basic four computer math symbols should be familiar to you by now:
Addition symbol: +
Subtraction symbol: –
Multiplication symbol: *
Division symbol: /
These doojabbies are common throughout computerdom. If you use a spread sheet, they’re the symbols you use to do math. All these symbols are clus tered about your keyboard’s numeric keypad. The most cryptic one is the asterisk (*), for multiplication.
Other than the symbols, the only thing worth keeping in mind about math in C is that the calculation always goes on the right side of the equal sign. Therefore:
meals=breakfast+lunch+dinner;
314 Part IV: C Level
This equation, assuming that everything is a numeric variable, is correct. The following statement, however, is a boo-boo:
breakfast+lunch+dinner=meals;
The math goes on the right side of the equal sign. Always.
Goofing up a math equation is where you get those horrid Lvalue errors.
You can always remember the cryptic mathematical symbols in the C language by looking at your keyboard’s numeric keypad; each of the symbols is right there.
Math problems in C work from left to right, the way you read. Some operations, however, have priority over others. If you forget, remember My Dear Aunt Sally, from Chapter 11.
Another mathematical symbol is the %, which means modulus. This dreadful topic is covered in Chapter 26, where it’s appropriate uses are apparent.
It can be said that a C language operator exists for every odd symbol, shape, jot, and tittle on your keyboard. This statement is almost true. Pray that you never have to memorize them all.
Taking your math problems to a higher power
Two mathematical operations that seem to be lacking in C’s granola of symbols are the power-of symbol and the square root symbol. Of course, I’m assuming that you give a hoot about either of them, but you never know when they may crop up.
The power-of thing deals with problems that contain the words squared and cubed in addition to power of. For example:
“Four squared” means 4 × 4, or 42. The latter reads “Four to the second power.”
“Four cubed” means 4 × 4 × 4, or 43. This one reads “Four to the third power.”
Beyond cubed, or to the third power, you just say the power number; So, 4 × 4 × 4 × 4 × 4 is 45, or “four to the fifth power.” (Don’t even bother trying to figure out the answer; the computer does it for you!)
Chapter 25: Math Madness! 315
Alas, there just isn’t any handy way to express 45 in C. There’s no cool symbol. For example, you cannot write
answer=4♠5;
This line just doesn’t work, even considering that ♠ isn’t a symbol anywhere on the keyboard (even in Las Vegas). It would be nice, but it just isn’t so.
You need to draw on the C language’s vast library of supplemental math func tions. A few dozen functions compute such things as power-of, square root, terrifying trigonometric functions, and so on (see Table 25-1, later in this chapter). To take a number to a higher power, you use the pow() function.
The pow() function is used to calculate one value taken to a certain power, such as 4 taken to the second power (42). Here’s the format:
value = pow(n,p)
In this line, value, n, and p all must be double-precision variables (defined using the double declaration). The pow() function calculates n to the p power. The answer is stored in the value variable.
To prevent your compiler from going mad, you must include the MATH.H header file at the beginning of your source code. Stick the following line up there somewhere:
#include <math.h>
This line is required for the pow function as well as for other math functions you may dare to use.
Putting pow() into use
Using the pow() function is easy — it’s just like using any other function. Just declare your variables as doubles, include the MATH.H thing, and you’re all set. Why not put it forth in one of those endearing math-sentence problems? To wit:
Suppose that you have tasked Milton — your brilliant, Mensa-club-leader son — with decorating the house for Christmas. Because he’s too smart to drive,
he directs you to go to the store and pick up 28 (“two to the eighth power”) twinkly lights. You quickly dash off to your computer and use the C language to decipher what he means:
316 Part IV: C Level
#include <stdio.h> #include <math.h>
int main()
{
double lights; |
|
lights=pow(2,8); |
/* figure 2 to the 8th power */ |
printf(“Milton, we need %0.f lights.\n”,lights); return(0);
}
Type this silly program on a new screen in your editor. Save the contraption to disk as LIGHTS1.C.
Compile and run.
If you get a linker error in your Unix-like operating system, please refer to the following sidebar, “Gotta link in that math library!”
Here’s the output:
Milton, we need 256 lights.
There. Now you both know how many lights are needed. The computer suc cessfully concluded that 28 is equal to 256.
Two to the eighth power is written out longways; thus:
2 x 2 x 2 x 2 x 2 x 2 x 2 x 2
The pow function expects to deal with double variables. In fact, many of the MATH.H functions deal with anything except integers.
Constant values, such as 2 and 8 inside LIGHTS1.C, don’t have to be doubles (or even typecast as doubles). Thankfully, the compiler is pretty smart about that stuff.
The printf() placeholder used for printing a floating-point number is %f. It works for both floats and doubles. The 0. part of %0.f tells printf() to format the floating-point output using only the part of the number on the left of the decimal.
Some languages and spreadsheets use the caret symbol (^) for power, as in 2^8 for 28. This technique doesn’t work in C. (The ^ in C is a bitwise exclusive OR logical operation, whatever that means.)