Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
52
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

128 Part II: Run and Scream from Variables and Math

Beyond the getchar() dilemma, the program uses seven putchar() functions to display Hello! (plus a newline character) to the screen. It’s a rather silly use of putchar(), but it works.

The putchar() function is used to display a single character on the screen.

You can also specify a character as an escape sequence or a code value with putchar() (see the next section).

Character Variables As Values

If you want, you can live your life secure in the knowledge that the char key­ word sets aside storage space for single-character variables and strings. That’s all well and good, and it gets you an A on the quiz. You can stop reading now, if you want.

The horrible truth is that a single-character variable is really a type of integer. It’s a tiny integer, but an integer nonetheless. The reason that it isn’t obvious is that treating a char as an integer is really a secondary function of the singlecharacter variable. The primary purpose of single-character variables is to store characters. But they can be used as integers. It’s twisted, so allow me to explain in detail.

The basic unit of storage in a computer is the byte. Your computer has so many bytes (or megabytes) of memory, the hard drive stores so many giga­ bytes, and so on. Each one of those bytes can be looked at as storing a single character of information. A byte is a character.

Without boring you with the details, know that a byte is capable of storing a value, from 0 to 255. That’s the range of an unsigned char integer: from 0 to 255 (refer to Table 9-1, in Chapter 9). Because a character is a byte, the char can also be used to store those tiny integer values.

When the computer deals with characters, it doesn’t really know an A from a B. It does, however, know the difference between 65 and 66. Internally, the computer uses the number 65 as a code representing the letter A. The letter B is code 66. In fact, all letters of the alphabet, number characters, symbols, and other assorted jots and tittles each have their own character codes. The coding scheme is referred to as ASCII, and a list of the codes and characters is in Appendix B.

Essentially, when you store the character A in a char variable, you place the value 65 into that variable. Internally, the computer sees only the 65 and, lo, it’s happy. Externally, when the character is “displayed,” an A shows up. That satisfies you and me, supposing that an A is what we want.

Chapter 10: Cook That C Variable Charred, Please 129

This is how char variables can be both integers and characters. The truth is, they are integers. However, they are treated like characters. The following program, WHICH.C, reads a character from the keyboard and displays it by using the printf() function. The trick with WHICH.C is that the character is displayed as both a character and a numeric, integer value. Such duality! Can you cope?

#include <stdio.h>

int main()

{

char key;

printf(“Press a key on your keyboard:”); key=getchar();

printf(“You pressed the ‘%c’ key.\n”,key); printf(“Its ASCII value is %d.\n”,key); return(0);

}

Save the file to disk, naming it WHICH.C.

Compile WHICH.C. If you get any errors, double-check the source code, fix it up, and recompile.

Run the final program. If you press the A key (and then Enter), the output on your screen looks something like this:

Press a key on your keyboard:A

You pressed the ‘A’ key.

Its ASCII value is 65.

The second printf() statement displays the key variable by using the %c placeholder. This placeholder tells printf() to display the variable as a char­ acter. In the third printf() statement, the variable is displayed by using the %d placeholder. That one tells printf() to display the variable as an integer value — which it does.

All letters of the alphabet, symbols, and number keys on the keyboard have ASCII codes.

ASCII code values range from 0 to 127.

Code values higher than 127 — from 128 to 255 — are called extended ASCII codes. Those characters aren’t standard on all computers, though they’re pretty consistent on Windows PCs. It’s just a technical snit.

Appendix B lists all the ASCII characters and their values.

Chapter 13 shows you how to “compare” one letter or ASCII character with another. What’s being compared is really the character’s code value, not its aesthetics.

130 Part II: Run and Scream from Variables and Math

Part III

Giving Your Programs the Ability to Run Amok

In this part . . .

The programs illustrated in the first two parts of this book have been top-down. That is, they are executed

one line after another, from top to bottom. They make no deviations and have no change in the pattern, no creativ­ ity, no choice. Boring! But computer programs can do more than that.

To really make a program run amok, you can place a deci­ sion machine inside of it. That decision machine lets the program do one thing or another based on a comparison, such as “If the user types L, then go left and get eaten

by the hungry elf.” It’s not a choice that the computer makes; the computer is dumb. But it’s an alternative, which means that the program is capable of more than just chomping through instructions, one after the other.

In addition to making decisions, the computer is good at doing things over and over — without complaining! Com­ bine decision-making with this love of repetition, and pretty soon you have programs that spin off into alternative uni­ verses, taking control of the computer with them! It’s runamok time!

Chapter 11

C More Math and the Sacred

Order of Precedence

In This Chapter

Reviewing the C math operators

Incrementing variables

Understanding the order of precedence

Introducing My Dear Aunt Sally

Using parentheses to control your math

Beware ye the dreadful math chapter! Bwaa-ha-ha!

Math is so terrifying to some people that I’m surprised there isn’t some math-themed horror picture, or at least a ride at Disneyland. Pirates. Ghosts. Screaming Dolls. Disneyland needs math in order to terrify and thrill children of all ages. Ludwig von Drake would host. But I digress.

This chapter really isn’t the dreadful math chapter, but it’s my first lecture that dwells on math almost long enough to give you a headache. Don’t panic! The computer does all the work. You’re only required to assemble the math in the proper order for the answers to come out right. And, if you do it wrong, the C compiler tells you and you can start over. No embarrassment. No recriminations. No snickering from the way-too-smart female exchange stu­ dent from Transylvania.

An All-Too-Brief Review of the Basic

C Mathematical Operators

Table 11-1 shows the basic C mathematical operators (or it could be arith­ metic operators — whatever). These symbols and scribbles make basic math happen in a C program.

134 Part III: Giving Your Programs the Ability to Run Amok

Table 11-1

 

C’s Mathematical Doodads

 

Operator

What You

As Pronounced

 

or Symbol

Expect

by Sixth Graders

Task

+

+

“Plus”

Addition

 

 

 

 

-

“Minus”

Subtraction

 

 

 

 

*

×

“Times”

Multiplication

/

÷

“Divided by”

Division

 

 

 

 

You use the symbols to do the following types of math operations:

Work with values directly:

total = 6 + 194;

The integer variable total contains the result of adding 6 and 194.

In this example:

result = 67 * 8;

the variable result (which can be either an integer or a float variable) contains the result of multiplying 67 by 8:

odds = 45/122;

The float variable odds contains the result of dividing 45 by 122:

In all cases, the math operation to the right of the equal sign is per­ formed first. The math is worked from left to right by the C compiler. The value that results is placed in the numeric variable.

Work with values and variables:

score = points*10;

The variable score is set equal to the value of the variable points times 10.

Work with just about anything; functions, values, variables, or any combination:

height_in_cm = atoi(height_in_inches)*2.54;

The variable height_in_cm is set equal to the value returned by the atoi function times 2.54. The atoi() function manipulates the variable height_in_inches (which is probably a string input from the keyboard).

Chapter 11: C More Math and the Sacred Order of Precedence 135

The math part of the equation is calculated first and is worked from left to right. The result is then transferred to the variable sitting on the left side of the equal sign.

The old “how tall are you” program

You can use “the power of the computer” to do some simple yet annoying math. As an example, I present the HEIGHT.C program, with its source code shown next. This program asks you to enter your height in inches and then spits back the result in centimeters. Granted, it’s a typically dull C language program. But, bear with me for a few pages and have some fun with it. Enter this trivial program into your editor:

#include <stdio.h> #include <stdlib.h>

int main()

{

float height_in_cm;

char height_in_inches[4];

printf(“Enter your height in inches:”); gets(height_in_inches);

height_in_cm = atoi(height_in_inches)*2.54;

printf(“You are %.2f centimeters tall.\n”,height_in_cm); return(0);

}

Be careful with what you type; some long variable names are in there. Also, it’s height, not hieght. (I mention it because I tried to compile the program with that spelling mistake — not once, but twice!) Save the file to disk as HEIGHT.C.

Compile the program. Watch for any syntax or other serious errors. Fix them if they crop up.

Run the HEIGHT program. Your output looks something like this:

Enter your height in inches:60

You are 152.40 centimeters tall.

If you’re 60 inches tall (5 feet exactly), that’s equal to 152.40 centimeters — a bigger number, but you’re still hovering at the same altitude. The program is good at converting almost any length in inches to its corresponding length in centimeters.

136 Part III: Giving Your Programs the Ability to Run Amok

Height. It has e before i. It’s another example of why English is the worstspelled language on the planet. (It’s your number-one typo possibility if you get a syntax error in the program.)

The atoi() function reaches into the string you enter and pulls out an integer value. And, it’s atoi(), not atio() (another reason, though invalid, to hate English spelling).

The atoi() function translates the value held in the string variable, height_in_inches, into an integer. Then that value is multiplied by 2.54. (The asterisk is used for multiplication.) The result is then slid through the equal sign and stored in the float variable, height_in_cm.

The value 2.54 is obviously a float because it contains a decimal part.

height_in_inches is an integer because that’s the type of value the atoi() function returns. When you multiply an integer by a float, how­ ever, the result is a float. That’s why the height_in_cm variable is a float.

An inch has 2.54 centimeters in. It’s not that this knowledge gets you anywhere, at least not in the United States. However, if you’re on Jeopardy! and the Final Jeopardy answer is 2.54, you’ll know the ques­ tion. (By the way, an easy mnemonic device for remembering how many centimeters are in an inch is to scream “two-point-five-four centimeters per inch” at the top of your lungs 30 times.)

A centimeter equals 0.39 inches. A centimeter is really about as long as your thumbnail is wide —as long as you don’t have colossal thumbs, of course.

Unethical alterations to the old “how tall are you” program

Though I’m not standing behind you, I can clearly see the HEIGHT.C program source code sitting in your editor. Good. Change Line 11 as follows:

height_in_cm = atoi(height_in_inches)*2.54*1.05;

After the 2.54 and before the semicolon, insert *1.05 (“times one point-oh- five”). This increases your height by five-hundredths of a centimeter for each centimeter you have in height. The result? Wait! Save the file and recompile it. Then run it again:

Enter your height in inches:60

You are 160.02 centimeters tall.

That may not mean much to you. But suppose that you’re corresponding with some French person who’s romantically interested in you. If so, you can tell him or her that, according to a program run on your computer, you’re

Chapter 11: C More Math and the Sacred Order of Precedence 137

160.02 centimeters tall. That means nothing to an American, but it means that you’re three whole inches taller in France. If you were 5'10" (70 inches), the program would produce the following:

Enter your height in inches:70

You are 186.69 centimeters tall.

Now, you’re 186.69 centimeters tall — or 6'112" tall! They’ll swoon!

And now, the confession:

The purpose of this discussion is not to tell you how to cheat when you’re programming a computer, nor is there any value in deceiving the French. For the most part, people who run programs want accurate results. However, it does show you the following:

height_in_cm = atoi(height_in_inches)*2.54*1.05;

The variable height_in_cm is equal to the result of three mathematical oper­ ations: First, an integer is produced based on the value of the string variable height_in_inches. That’s multiplied by 2.54, and the result is multiplied again by 1.05.

Having a long mathematical formula is perfectly okay in C. You can add, mul­ tiply, divide, and whatnot all the time. To ensure that you always get the result you want, however, you must pay special attention to something called the order of precedence. That’s the topic of a section later in this chapter.

An equation in C can have more than two items. In fact, it can have a whole chorus line of items in it. The items must all be on the right, after the equal sign.

To increase the height value by .05 (five-hundredths, or 5 percent), the

number must be multiplied by 1.05. If you just multiply it by .05, you decrease it by 95 percent. Instead, you want to increase it by 5 percent, so you multiply it by 105 percent, or 1.05. I stumbled on this knowledge accidentally, by the way.

The Delicate Art of Incrementation (Or, “Just Add One to It”)

The mathematical concept of “just add 1 to it” is called incrementation. You move something up a notch by incrementing it — for example, shifting from first to second, racking up another point in Gackle Blaster, or increasing your compensation by a dollar an hour. These are examples of incrementation.