11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

28 Part I: Introduction to C++ Programming(x + 2) = y / 2x + 4 = ysolve for x and yAny reader who’s had algebra realizes right off that the mathematician hasintroduced the variables x and y. But C++ isn’t that smart (computers may befast, but they’re stupid).You have to announce each variable to C++ before you can use it. You have tosay something soothing like this:int x;x = 10;int y;y = 5;These lines of code declare that a variable x exists, that it is of type int, andthat a variable y of type int also exists. (The next section discusses variabletypes.) You can declare variables (almost) anywhere you want in yourprogram — as long as you declare the variable before you use it.Declaring Different Types of VariablesIf you’re on friendly terms with math (hey, aren’t we all?), you probably thinkof a variable in mathematics as an amorphous box capable of holding whateveryou might choose to store in it. You might easily write something like thefollowing:x = 1x = 2.3x = “this is a sentence”x = TexasAlas, C++ is not that flexible. (On the other hand, C++ can do things that peoplecan’t do, such as add a billion numbers or so in a second, so let’s not get toouppity.) To C++, there are different types of variables just as there are differenttypes of storage bins. Some storage bins are so small that they can only handlea single number. It takes a larger bin to handle a sentence. Of course, no bin islarge enough to hold Texas (maybe Rhode Island or Delaware).You have to tell C++ what size bin you need before you can use a C++ variable.In addition, different types of variables have different properties. So far, youhave only seen the int type of variable in this chapter:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!