- •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
36 |
Part I: Introduction to C Programming |
The Helpful RULES Program
I just can’t let you go without a program in this chapter. To help you under stand the most easily offended C rules, I have summarized them in the follow ing program. It displays several lines of text that remind you of the basic rules of C that you know about:
#include <stdio.h>
int main()
{
printf(“Braces come in pairs!”); printf(“Comments come in pairs!”);
printf(“All statements end with a semicolon!”); printf(“Spaces are optional!”);
printf(“Must have a main function!”); printf(“C is done mostly in lowercase.\ It’s a case-sensitive language.”);
return(0);
}
Type the preceding source code into your editor. Save the code to disk as
RULES.C. Compile and run.
The resulting program is named RULES, and you can run it whenever you need a reminder about some basic C do’s and don’ts.
This program is really no different from those shown in previous chap ters. It merely has more printf() functions.
The final printf() function (in Line 10) may seem a little odd. That’s because it’s split between two lines. This weird contraption is covered later in this chapter.
The importance of being \n
Did you notice something odd about the output of the RULES program? Yes, it resembles an ugly clot of text:
Braces come in pairs!Comments come in pairs!All statements end with a semicolon!Spaces are optional!Must have
a main function!C is done mostly in lowercase. It’s a case-sensitive language.
The source code looks okay, but what’s missing from the output is the char acter you get when you press the Enter key, or what’s called the newline char acter. You have seen it before. It’s that weird \n thing:
Chapter 3: C Straight 37
\n
This line is C-speak for “Gimme a new line of text.” The n stands for new in new line (though they write it as one word: newline).
The program you just created, RULES.C, needs the \n character at the end of each line to ensure that each line is displayed on a line by itself on the screen. This addition makes the output of the RULES program easy to read.
Edit the RULES.C source code file again. Before the last double-quote in each printf() string, add the \n newline character.
If you’re good with search and replace, search for the “) (quote-paren) and replace it with \n”).
Save the file to disk and recompile it. The output should now be more pleasing:
Braces come in pairs! Comments come in pairs!
All statements end with a semicolon! Spaces are optional!
Must have a main function!
C is done mostly in lowercase. It’s a case-sensitive language.
In C, the \n character is used in a text string as though the Enter key were pressed.
It’s always \n with a little n. C is mostly lowercase.
The \n is called newline, though calling it “slash-n” or “backslash-n” is acceptable as long as you don’t say it aloud.
Table 24-1, in Chapter 24, lists other characters of a similar nature to \n.
Breaking up lines\ is easy to do
Another anomaly of the RULES program is that rogue \ character found at the end of the tenth line. When used to end a line, the sole \ tells the compiler that the rest of the line is merely continued on the line that follows. So, these two lines:
printf(“C is done mostly in lowercase\
It’s a case-sensitive language.\n”);
are both seen as one single line when it comes time to compile; all the compiler sees is this:
printf(“C is done mostly in lowercase It’s a case-sensitive
language.\n”);
38 |
Part I: Introduction to C Programming |
You may find such a trick necessary for extra-long lines as your programs grow more complex. The \ simply lets you split up a long line between several lines in your source code. That can be handy.
Depending on how your editor and compiler behave, the result of splitting a line with a string of text in it may not be what you want. For example, the output on your screen may look like this:
Braces come in pairs! Comments come in pairs!
All statements end with a semicolon! Spaces are optional!
Must have a main function!
C is done mostly in lowercase. It’s a casesensitive language.
That happens because the split line includes a few tabs to indent things — which looks pretty in your source code, but looks like blech when the pro gram runs. The solution is merely to edit the source code so that the extra tabs are removed from the string of text.
To wit, change Lines 10 and 11 in the source code from this:
printf(“C is done mostly in lowercase.\
It’s a case-sensitive language.”);
to this:
printf(“C is done mostly in lowercase. \
It’s a case-sensitive language.”);
Note the extra space after the period in the first line (before the backslash), which keeps the two lines of text from running into each other. Save that mess. Compile and run. The output shall be most pleasing to the eye.
Do note that some programs elsewhere in this book may use the \ to split long lines.
Don’t worry about using the \ to split any lines. It’s a trick you see others use occasionally, but in my travels I prefer using a sideways-scrolling editor to splitting up long lines.
Although split lines are treated as a single line, any errors that happen on
either line are given their proper line number in the source code file. So, if a semicolon were missing at the end of Line 11 in the RULES.C example, the compiler would flag it on that line, not on the line before it.
Chapter 4
C What I/O
In This Chapter
Reading the keyboard
Understanding printf()
Creating formatted output
Understanding scanf()
Computers are all about input and output — the old I/O of days gone by, what the pioneers once sang about. The wimminfolk would want to dance
real slow. Maybe cry. It was a sentimental thing, y’all — something that fancy, dooded-up city slickers read about in dime magazines.
A-hem!
Input and output: You type something in and get a response, ask a question and get an answer, put in two dollars in coins and get your soda pop — things along those lines. This goes along with what I present in Chapter 3: It is your job as a programmer to write a program that does something. At this point in the learning process, triviality is okay. Soon, however, you begin to write pro grams that really do something.
Introduce Yourself to Mr. Computer
To meet the needs of input and output — the old I/O — you can try the follow ing program, WHORU.C — which is “who are you” minus a few letters. Please don’t go calling this program “horror-you” (which could be spelled another way, but this is a family book).
40 |
Part I: Introduction to C Programming |
The purpose of this program is to type your name at the keyboard and then have the computer display your name on the screen, along with a nice, friendly greeting:
#include <stdio.h>
int main()
{
char me[20];
printf(“What is your name?”); scanf(“%s”,&me);
printf(“Darn glad to meet you, %s!\n”,me);
return(0);
}
Type the preceding source code into your editor. Double-check everything.
Don’t bother with any details just yet. Type and hum, if it pleases you.
Save the file to disk. Name it WHORU.C.
Don’t compile this program just yet. That happens in the next section.
The char me[20]; thing is a variable declaration. It provides storage for the information you enter (the I in I/O). You find out more about variables in Chapter 8.
The new function here is scanf(), which is used to read input from the keyboard and store it in the computer’s memory.
Left paren is the ( character. Right paren is the ) character. Paren is short for parenthesis or a type of steak sauce. (It’s also not a “real” word and is frowned on by English teachers of the high-and-tight bun.)
Compiling WHORU.C
Compile the WHORU.C source code. If you see syntax or other errors, doublecheck your source code with what is listed in this book. Ensure that you entered everything properly. Be on the lookout for jots and tittles — parentheses, double quotes, backslashes, percent signs, sneeze splotches, or other unusual things on your monitor’s screen.
If you need to fix any errors, do so now. Otherwise, keep reading in the next section.