- •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
306 Part IV: C Level
The Old Displaying-Text-with-printf()
Routine
Printf()’s main purpose in life is to display text on the screen. Here is its most basic format:
printf(“text”);
text is the text you want to see on the screen. It’s enclosed in double quotes. The double quotes are enclosed in parentheses, and the entire statement must end with a semicolon.
Special characters — such as a double quote, tab, backspace, and Enter (a new line) — can be included in the text that printf() displays. These characters require the printf() escape sequences, as described in the next section.
printf() can display two or more lines of text by using the \n (new line) escape sequence.
To specify a double quote in your text string, use the \” escape sequence.
The printf() Escape Sequences
Table 24-1 lists many of the printf() escape sequences. Most of these you know from using them. Others are very specific, and you may never ever use them in your entire programming life.
Table 24-1 |
printf() Escape Sequences |
Sequence |
Shortcut for or Equivalent to |
\a |
Beeps the speaker |
|
|
\b |
Backspace (moves the cursor back, no erase) |
|
|
\f |
Form feed (ejects printer page; may clear the screen on |
|
some computers) |
|
|
\n |
Newline, like pressing the Enter key |
|
|
\r |
Carriage return (moves the cursor to the beginning of the line) |
|
|
|
|
|
Chapter 24: The printf() Chapter 307 |
|
|
|
|
||
|
|
|
|
|
|
Sequence |
Shortcut for or Equivalent to |
|
|
|
\t |
Tab |
||
|
|
|
|
|
|
\v |
Vertical tab (moves the cursor down a line) |
||
|
|
|
|
|
|
\\ |
The backslash character |
||
|
|
|
|
|
|
\’ |
The apostrophe |
||
|
|
|
|
|
|
\” |
The double-quote character |
||
|
|
|
|
|
|
\? |
The question mark |
||
|
|
|
|
|
|
\0 |
The “null” byte (that’s 0, not the letter O) |
||
|
|
|
|
|
|
\Onn |
A character value in octal (base 8) |
||
|
|
|
|
|
|
\xnnn |
A character value in hexadecimal (base 16) |
||
|
|
|
|
|
The final two items in Table 24-1 are the most flexible. They allow you to insert any character into any text after you know that character’s octal or hexadecimal code value.
Suppose that you need to display the Escape character in your text. A quick look into Appendix B shows that the hexadecimal code for Escape is 1b. As an escape sequence — an Escape escape sequence — that would be written as
\x1b
Here’s how it would look in printf():
printf(“On some consoles, this clears the screen \x1b[2J”);
You may want to flag this page with a sticky note or dog-ear the corner. The page has stuff no one remembers, so you wind up referring to Table 24-1 often.
The printf() escape-sequence testing program deluxe
To see how some of these characters work, create the PRINTFUN.C program, listed next. You modify the printf() statement at the core of the program to demonstrate how the various escape sequences affect text:
308 Part IV: C Level
/*
printf() escape sequence demonstration program */
#include <stdio.h>
int main()
{
printf(“Here is the \\a sequence: \a”); getchar();
return(0);
}
Enter this program into your text editor. Save it to disk as PRINTFUN.C.
Compile and run PRINTFUN.C. Its purpose is to see how the \a sequence “appears” in the text that’s displayed. Here’s a sample of the program’s output:
Here is the \a sequence: BEEP!
The speaker beeps. How ghastly! Pray that you’re not testing this program in the early afternoon, or else you may wake up your cellmates.
When the program runs, getchar() waits for you to press a key at the keyboard. This pause allows you to examine the output before the pro gram quits.
The text string in printf() contains two escape sequences. The first is \\, a double backslash that displays the backslash character. In this example, \\a displays \a — the escape sequence being tested. The second escape sequence is at the end of the string, \a.
Notice that the string in printf doesn’t end in \n. The newline charac ter would goof up the display for some of the fancier escape sequences (\r, \t, and \b).
Putting PRINTFUN to the test
The true test of the PRINTFUN program is to reedit it and replace the \\a and \a with another escape sequence. This way, you can test all the sequences to get a feel for what each of them does.
Begin by replacing Line 9 in the program with this one:
printf(“Here is the \\b backspace sequence:\b\b\b\b”);
Chapter 24: The printf() Chapter 309
This line tests the \b, backspace, escape sequence. Save the changes to the program, compile it, and run it.
You see the cursor sitting below the n in sequence when the program runs. That’s because \b backs up the cursor but does not erase.
There are four instances of \b, which back up the cursor four places from the end of the line. (If the cursor isn’t right there, you have a rogue space in the program or you specified more or fewer instances of \b.)
The \n character you’re familiar with, but what does \r do? How is a carriage return different from a new line? Edit Line 9 in PRINTFUN.C to look like this and find out:
printf(“Here is the \\r sequence:\r”);
Save the change to disk, compile, and run.
In the output, you see the cursor flashing under the H at the beginning of the line. The carriage return resembles the carriage return on a typewriter: It moves you to the beginning of the line. It was only by whacking the line-feed bar on a typewriter that the page was advanced.
The \t character produces a tab, like pressing the Tab key. The cursor moves a predefined number of characters to the left. This is good for producing a table in which text has to be lined up. Edit Line 9 in the program to read:
printf(“Able\tBaker\tCharlie\n”);
Then, insert the following lines immediately after the preceding printf() statement:
printf(“1\t2\t3\n”);
printf(“Alpha\tBeta\tGamma\n”);
No spaces are in this printf text string. The words Able, Baker, and Charlie are separated by \t (tab) escape sequences. The line ends with \n, the newline. The same holds true for the two new lines: instances of \t separate the numbers and words.
Double-check your source code! Ensure that you have \t twice in each printf() statement and that \n ends each quoted string of text. Beware of rogue backslashes, which you have a tendency to type as you enter each line. When everything looks okay, save the PRINTFUN.C source code file to disk. Compile it. Run it. Here’s some sample output: