2.3. VariablesΒΆ
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a named location that stores a value.
Just as there are different types of values (integer, character, etc.), there are different types of variables. When you create a new variable, you have to declare what type it is.
Note
In C++, integer variables are declared as type int
and character variables
are declared as type char
.
The following statement creates a new variable named fred that has type char
.
char fred;
This kind of statement is called a declaration.
The type of a variable determines what kind of values it can store. A
char
variable can contain characters, and it should come as no surprise
that int
variables can store integers.
There are several types in C++ that can store string
values, but we are
going to skip that for now (see Chapter 7).
To create an integer variable, the syntax is
int bob;
where bob is the arbitrary name you made up for the variable. In general, you will want to make up variable names that indicate what you plan to do with the variable. For example, if you saw these variable declarations:
char firstLetter;
char lastLetter;
int hour, minute;
you could probably make a good guess at what values would be stored in
them. This example also demonstrates the syntax for declaring multiple
variables with the same type: hour and minute are both integers (int
type).
int main() { int x = 7; int y = 10; char c = '8'; while (x < y) { cout << c << endl; x++; } double d = 9; int z = x + y; cout << "It's the year " << 2000 + z << "!"; }
int main() { char init1 = 'K'; string init2 = "T"; cout << init1 << "+" << init2 << endl; string init3 = "C"; char init4 = 'J'; cout << init3 << '+' << init4 << endl; string c = "Carved their initials in a tree!"; cout << c; }
-
Q-5: Match the variable to the kind of value it can store.
Ideally, you want your variables to be named according to what they represent. Not the case here! Try again!
- char joe;
- 'x'
- string ten;
- "Joe"
- int x;
- 10
Write code that creates the variables name, firstInitial, and numberOfSiblings IN THAT ORDER. It is up to you to choose the correct types for these variables.