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

88

Part II: Run and Scream from Variables and Math

Why the multiplication symbol is an asterisk (if you care to know)

In school, you probably learned that the X symbol means multiply. More properly, it’s the × symbol, not the character X (or even little x). It’s pro­ nounced “times,” as in “four times nine” for 4×9. In higher math, where it was harder for you to get an “easy A,” the dot was also used for mul­ tiplication: 4•9 for “four times nine.” I have even seen that expressed as 4(9) or (4)(9), though I fell right back asleep.

Why can’t computers use the X? Primarily because they’re stupid. The computer doesn’t

know when you mean X as in “ecks” and × as in “times.” So, the asterisk (*) was accepted as a substitute. (The keyboard has no dot • character either.)

Using the * for multiplication takes some getting used to. The slash is kind of common — 3/$1 for “three for a dollar” or 33 cents each — so that’s not a problem. But the * takes some chanting and bead counting.

It just doesn’t work in the C language. The preceding line tells the C compiler to take the value of the var variable and put it into some numbers. Huh? And that’s the kind of error you see when you try it: Huh? (It’s called an Lvalue error, and it’s shamefully popular.)

More mathematical symbols, or operators, are used in C programming. This chapter introduces only the four most common symbols.

Having trouble remembering the math operators? Look at your keyboard’s numeric keypad! The slash, asterisk, minus, and plus symbols are right there, cornering the number keys.

Unlike in the real world, you have to keep in mind that the calculation is always done on the right, with the answer squirted out the equal sign to the left.

You don’t always have to work with two values in your mathematical functions. You can work with a variable and a value, two variables, functions — lots of things. C is flexible, but at this stage it’s just impor­ tant to remember that * means “multiply.”

How much longer do you have to live to break the Methuselah record?

The following METHUS4.C source code uses a bit of math to figure out how many more years you have to live before you can hold the unofficial title of the oldest human ever to live (or at least tie with him).

Chapter 7: A + B = C 89

Before you do this, I want you to think about it. What are the advantages of being the oldest person ever to live? What else do we know about Methuselah? He died before the flood. He was a good man, well received by The Man Upstairs. But, what else? I mean, like, did he eat weird or some­ thing? Did he avoid the grape? The Bible offers no hints.

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

int main()

{

int diff; int methus; int you;

char years[8];

printf(“How old are you?”);

gets(years);

you=atoi(years);

methus=969;

/* Methuselah was 969 years old */

diff=methus-you;

printf(“You are %d years younger than Methuselah.\n”,diff);

return(0);

}

The METHUS4.C program is eerily similar to METHUS3.C. It has only a few deviations, so you can edit the METHUS3.C source code and then save it to disk as METHUS4.C. Cross-check your work with the preceding source code listing, just to be sure.

Compile the program. Fix any errors that may crop up. Then run the final product. Your output may look something like the following:

How old are you?29

You are 940 years younger than Methuselah.

Try entering a different age to see how it compares with Methuselah’s.

It does math! It does math!

This program uses four — four! — variables: diff, methus, and you are all integer variables. years is a string variable.

What happens if you enter a negative age — or an age greater than 969?

90

Part II: Run and Scream from Variables and Math

To figure out how much longer you have to live to match Methuselah’s record, you subtract your age from his. Pay special attention to the order of events in the following statement:

diff=methus-you;

The math part always goes on the right side of the equal sign. Your age, stored in the you numeric variable, is subtracted from Methuselah’s and stored in the diff numeric variable. The result then slides through the equal sign and into the diff numeric variable.

Bonus modification on the final

Methuselah program!

Methuselah works hard until he’s 65, and then he retires. Because he got his first job at 19, he has been contributing to Social Security. As soon as he hits 65, he starts drawing his money out. And out. And out. And out some more.

How about writing a program that can do what no bureaucrat in Washington can do: Figure out how much money Methuselah is drawing from the system? (We leave the “whether he earned it all” question up to future generations because, of course, if you ask Methuselah himself, he says that he did.)

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

int main()

{

int contributed; int received;

contributed=65-19; received=969-65;

printf(“Methuselah contributed to Social Security for %i years.\n”,contributed);

printf(“Methuselah collected from Social Security for %i years.\n”,received);

return(0);

}

Type into your editor the source code for METHUS5.C — which I promise is the last of the Methuselah suite of programs. Double-check your typing and all that stuff.

Your fine sense of logic wants you to type i before e in received, though the illogic of English dictates otherwise.

Save the file as METHUS5.C.

Chapter 7: A + B = C 91

Compile it! Check for any errors or small pieces of meat the compiler may choke on. Dislodge them (reedit the source code) and compile again if you need to.

Run the program! Here’s a sample of the output:

Methuselah contributed to Social Security for 46 years.

Methuselah collected from Social Security for 904 years.

It seems fair to him.

Line 10 calculates how long Methuselah has been receiving Social Security. If he died at 969 and began receiving checks at 65, the differ­ ence is the value you want. That’s stored in the received variable.

Notice how the smaller value is subtracted from the larger? C works from left to right with math: 65 minus 19; 969 minus 65. Still, the math part of the equation must be on the right. The variable that holds the result is on the left.

When math is used in a program with numbers rather than variables, the numbers are called constants.

You can find more information on the subject of constants in Chapter 8.

The direct result

Are variables necessary? Yes, when the value isn’t known. In the last few Methuselah programs, the values were known, for the most part. Only when you enter your own age is there truly a need for a variable. Otherwise, con­ stant values can be used.

For example, the following program is another version of METHUS5. You don’t have to type this program, but look at the only two statements in the program. Gone are the variables and the statements that assigned them values, as well as the #include <stdlib.h> because atoi() isn’t being used:

#include <stdio.h>

int main()

{

printf(“Methuselah contributed to Social Security for

%d years.\n”,65-19);

printf(“Methuselah collected from Social Security for %d years.\n”,969-65);

return(0);

}

92

Part II: Run and Scream from Variables and Math

The %d in the first printf() function looks for an integer value to “fill in the blank.” The printf() function expects to find that value after the comma — and it does! The value is calculated by the C compiler as 65–19, which is 46.

The printf() statement plugs the value 46 into the %d’s placeholder. The same holds true for the second printf() function.

You can do the same thing without the math. You can figure out 65–19 and 969–65 in your head and then plug in the values directly:

printf(“Methuselah contributed to Social Security for %d years.\n”,46);

printf(“Methuselah collected from Social Security for %d years.\n”,904);

Again, the result is the same. The %d looks for an integer value, finds it, and plugs it in to the displayed string. It doesn’t matter to printf() whether the value is a constant, a mathematical equation, or a variable. It must, however, be an integer value.

Chapter 8

Charting Unknown Cs

with Variables

In This Chapter

Declaring variables

Naming variables

Using float variables

Declaring several variables at once

Understanding constants

Creating constants with #define

Using the const keyword

Variables are what make your programs zoom. Programming just can’t get done without them. You may have just dabbled with variables, but not

been formally introduced. In this chapter, you’re formally introduced!

Cussing, Discussing, and Declaring

Variables

Along comes Valerie Variable. . . .

Valerie is a numeric variable. She loves to hold numbers — any number — it doesn’t matter. Whenever she sees an equal sign, she takes to a value and holds it tight. But see another equal sign, and she takes on a new value. In that way, Valerie is a little flaky. You could say that Valerie’s values vary, which is why she’s a variable.

94

Part II: Run and Scream from Variables and Math

Victor is a string variable. He contains bits of text — everything from one char­ acter to several of them in a row. As long as it’s a character, Victor doesn’t mind. But which character? Victor doesn’t care — because he’s a variable, he can hold anything.

Yes, I have a point here. C has two main types of variables: numeric vari­ ables, which hold only numbers or values, and string variables, which hold text, from one to several characters long.

The C language has several different types of numeric variables, depend­ ing on the size and precision of the number. The details are in Chapter 9.

Before you use a variable, it must be declared. This is — oh, just read the next section.

“Why must I declare a variable?”

You’re required to announce your variables to the C compiler before you use them. You announce them by providing a list of variables near the top of the source code. That way, the compiler knows what the variables are called and what flavor of variables they are (what values they can contain). Officially, this process is known as declaring your variables.

For example:

int count; char key;

char lastname[30];

Three variables are declared in this example: an integer variable, count; a character variable, key; and a character variable, lastname, which is a string that can be as many as 30 characters long.

Declaring variables at the beginning of the program tells the compiler several things. First, it says “These things are variables!” That way, when the compiler sees lastname in a program, it knows that it’s a string variable.

Second, the declarations tell the compiler which type of variable is being used. The compiler knows that integer values fit into the count variable, for example.

Third, the compiler knows how much storage space to set aside for the vari­ ables. This can’t be done “on the fly,” as the program runs. The space must be set aside as the program is created by the compiler.