- •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! 317
Gotta link in that math library!
If you’re using Unix, Linux, or Mac OS X, you need to know that GCC isn’t normally configured to do high-level math functions, such as pow() and sqrt(). The reason is that the standard C library doesn’t come with those math functions in it. The advantage is that programs produced with the standard library are small. The disad vantage is that you need to remember to link in the math library when you write programs that use math.
The standard math library in C is named libm, but you can link it into your program by modify ing the gcc command:
gcc -lm source.c -o output
Follow gcc with the -lm switch. This switch tells GCC to also link in the libm math library along with the standard library. The input file is source.c, and the output file is output. To properly compile lights1.c:
gcc -lm lights1.c -o lights1
Again, this option is necessary only for pro grams that use high-level math functions. To confirm, use the man command to look up the function:
man sqrt
It says, right there on top, under the LIBRARY heading, that the standard math library must be linked in to make the function work.
Rooting out the root
Another math problem you may have to work out is the square root. For the life of me, I can’t cite a practical example because, honestly, I find all math stupid. In any event, no keyboard symbol in C is used to calculate the square root of a number. As with the power-of deal, you use a special func tion: sqrt().
The sqrt() function is used to divine the square root of a number — to find out which number, when multiplied by itself, equals the number you want the square root of. Something like that. In any event, it’s not the “squirt” function. Here’s the format:
value = sqrt(n)
The double variable value is equal to the square root of the double variable n. Yes, everything must be double here. You also need the following include at the beginning of your source code:
#include <math.h>
318 Part IV: C Level
The only limitation on the sqrt() function is that n, the number you’re find ing the root of, cannot be negative. Even though my Vulcan friends tell me that there is such a thing, I would be leery of attempting it in the C language.
Because you and Milton have this light thing going, you’re going to surprise him by telling him the square root of the number of lights you bought for Christmas. To make that process easier, you devise the LIGHTS2.C program.
Type this program into your editor. Be careful when you’re typing because that long printf() line was split in order to fit into this book’s format; the single backslash is used to show that the line continues on the following line:
#include <stdio.h> #include <math.h> #define TOOTH 253
int main()
{
double lights; |
|
lights=sqrt(256); |
/* square root of 256 */ |
printf(“Milton, I got your %0.f%c lights.\n”,\ lights,TOOTH);
return(0);
}
Save this puppy to disk as LIGHTS2.C:
Compile and run. (Unix users, refer to the preceding sidebar, “Gotta link in that math library!” for more details.)
Milton, I got your 162 lights.
The sqrt() function boasts that the square root of 256 is 16. Or, to put it another way, 162 (or 16 × 16) is equal to 256. Milton would be pleased.
The square root of 256 is 16, and 16 squared (162) is 256. Is math great or what?
Character code 253 is equal to the tiny 2 — the squared number.
Character code 251 is equal to the traditional square root symbol. Even if you can manage to get that symbol into your text editor, you still need the sqrt() function to wrangle up a square root.
In some cases, codes 253 and 251 may not display the same symbol as described in the two preceding notes. Oh, well.
The %c in the printf() formatting string is used to bring in the special character, 253, defined as TOOTH earlier in the source code.