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

Chapter 7

A + B = C

In This Chapter

Changing a variable’s value

Introducing the int

Converting text with the atoi() function

Using +, -, *, and /

Struggling with basic math

It’s time to confirm your worst fears. Yes, computers have something to do with math. But it’s more of a passing fancy than the infatuation you’re now dreading. Unless you’re some hard-core type of engineer (the enginerd), math­ ematics plays only a casual role in your programs. You add, subtract, divide,

multiply, and maybe do a few other things. Nothing gets beyond the skills of anyone who can handle a calculator. It’s really fourth-grade stuff, but because we work with variables— which is more like eighth-grade algebra stuff — this material may require a little squeezing of the brain juices. In this chapter, I try to make it as enjoyable as possible for you.

The Ever-Changing Variable

A variable is a storage place. The C compiler creates the storage place and sets aside room for you to store strings of text or values — depending on the type of storage place you create. You do this by using a smattering of C lan­ guage keywords that you soon become intimate with.

What’s in the storage place? Could be anything. That’s why it’s called a vari­ able. Its contents may depend on what’s typed at the keyboard, the result of some mathematical operation, a campaign promise, or a psychic prediction. The contents can change too — just like the psychic prediction or campaign promise.

76

Part II: Run and Scream from Variables and Math

It’s by juggling these variables that work gets done in most programs. When you play PacMan, for example, his position on the screen is kept in a vari­ able because, after all, he moves (his position changes). The number of points PacMan racks up are stored in a variable. And, when you win the game, you enter your name, and that too is stored in a variable. The value of these items — PacMan’s location, your points, your name — are changing or can change, which is why they’re stored in variables.

Variables are information-storage places in a program. They can con­ tain numbers, strings of text, and other items too complex to get into right now.

The contents of a variable? It depends. Variables are defined as being able to store strings of text or numbers. Their contents depend on what happens when the program runs, what the user types, or the computer’s mood, for example. Variables can change.

Where are variables stored? In your computer’s memory. This informa­ tion isn’t important right now; the computer makes room for them as long as you follow proper variable-creating procedures in your C programs.

Strings change

The following program is brought to you by the keyword char and by the printf() and gets() functions. In this program, a string variable, kitty, is created, and it’s used twice as the user decides what to name her cat. The changing contents of kitty show you the gist of what a variable is:

#include <stdio.h>

int main()

{

char kitty[20];

printf(“What would you like to name your cat?”);

gets(kitty);

printf(“%s is a nice name. What else do you have in mind?”,kitty);

gets(kitty);

printf(“%s is nice, too.\n”,kitty); return(0);

}

Enter the source code for KITTY.C into your text editor. Save the file to disk as KITTY.C.

Chapter 7: A + B = C 77

Compile KITTY.C. If you get any errors, reedit your source code. Check for missing semicolons, misplaced commas, and so on. Then recompile.

Running the program is covered in the next section.

The char keyword is used to create the variable and set aside storage for it.

Only by assigning text to the variable can its contents be read.

It’s the gets() function that reads text from the keyboard and sticks it into the string variable.

Running the KITTY

After compiling the source code for KITTY.C in the preceding section, run the final program. The output looks something like this:

What would you like to name your cat?Rufus

Rufus is a nice name. What else do you have in mind?Fuzzball

Fuzzball is nice, too.

The kitty variable is assigned one value by using the first gets() function. Then, it’s assigned a new value by the second gets() function. Though the same variable is used, its value changes. That is the idea behind variables.

A single variable can be used many times in a program. It can be used over and over with the same value, or used over and over to store differ­ ent values.

It’s the contents of the string variable that are displayed — not the vari­ able name. In the KITTY.C program, the variable is named kitty. That’s for your reference as a programmer. What’s stored in the variable is what’s important.

Welcome to the Cold World of

Numeric Variables

Just as strings of text are stored in string variables, numbers are stored in numeric variables. This allows you to work with values in your program and to do the ever-dreaded math.

78

Part II: Run and Scream from Variables and Math

To create a numeric variable and set aside storage space for a number, a spe­ cial C language keyword is used. Unlike char, which creates all types of strings, different keywords are used to create variables for storing different types of numbers. It all depends on how big or how weird the number is.

Hello, integer

To keep things sane for now, I show you only one of the numeric variable types. It’s the simplest form of a number, the integer. Just say “IN-tuh-jur.” Integer.

Here’s how the typical C compiler defines an integer type of number:

An integer is a whole number — no fractions, decimal parts, or funny stuff.

An integer can have a value that ranges from 0 to 32,767.

Negative numbers, from –32,768 up to 0 are also allowed.

Any other values — larger or smaller, fractions, or values with a decimal point, such as 1.5 — are not integers. (The C language can deal with such numbers, but I don’t introduce those types of variables now.)

To use an integer variable in a program, you have to set aside space for it. You do this with the int keyword at the beginning of the program. Here’s the format:

int var;

The keyword int is followed by a space (or a press of the Tab key) and then the name of the variable, var. It’s a complete statement in the C language, and it ends with a semicolon.

Some compilers may define the range for an int to be much larger than –32,768 through 32,767. To be certain, check with your compiler’s docu­ mentation or help system.

On older, 16-bit computers, an integer ranges in value from –32,768 through 32,767.

On most modern computers, integer values range from –2,147,483,647 through 2,147,483,647.

More information about naming a variable — and other C language trivia about variables — is offered in Chapter 8. For now, forgive me for the unofficial introduction.