Chapter 2
Chapter 2
Variables
The HelloWorld programs from the previous chapter are simple and do not store or manipulate data. A
typical computer program stores and manipulates many kinds of data. The data must be stored in
memory locations in internal memory while the program is executing. In this chapter, we will describe
how memory locations are used in a computer program to store different types of data such as integer
values (i.e., whole numbers), floating-point numbers (i.e., numbers which have a “decimal” point), and
strings (sequences of characters). These memory locations are called variables and we will describe how
to reserve memory for variables, assign values to them, and display their values on the monitor.
Let’s suppose that we want to write a computer program to calculate the amount of carpet required to
cover a rectangular room of width 10 metres and length 15 metres. Memory locations can be used to
store the value of the width of the room and the value of the length of the room. An important property
of a memory location is that it can only store one value at a time. So, we will need one memory location
to store the width of the room and another memory location to store the length of the room. We will
also need a memory location to store the amount of carpet required (which is really the area of the
room). Figure 2.1 gives a snapshot of memory containing the three memory locations:
10 15
Since there are several memory locations, it is important to give each memory location a name so that it
can be uniquely identified within the program. Thus, we can give the memory location with the value 10
the name “width”, the one with the value 15 the name “length”, and the third one to store the amount
of carpet (or area of the room), the name “area”.
1
When we give a name to refer to a memory location, the name is called a variable, i.e., a variable is a
name used to refer to a specific memory location. Thus, width, length, and area are variables. The term
“variable” is used since the value in the memory location can vary or change over time. Figure 2.2 is a
picture of memory with the named memory locations or variables:
width length
10 15
area
If you wish to reserve a memory location to store an integer quantity and give it a name, the name for
that memory location (i.e., variable) must be declared. Declaring an integer variable tells the computer
to reserve a memory location to store an integer value and give it the name you specified.
The keyword int is used to declare an integer variable. To declare that width, length, and area are
integer variables, the following statements should be written, before each variable is used:
int width;
int length;
int area;
2
If a variable is used in a program but has not been declared, the compiler will generate an error
indicating that the variable was not declared. This error is easy to correct by declaring the variable.
In Figure 2.2, the width variable is shown with the value 10 and the length variable is shown with the
value 15. But, how did these values get into these memory locations? We will now explain how to put
(or write) a value in a memory location. Writing a value to a named memory location is done by using
assignment statements. There are two parts of an assignment statement, the value you want to store
(or write) and the name of the memory location where the value will be stored.
For example, to store the value 10 in the variable width, the following statement is used:
width = 10;
Similarly, to store the value 15 in the variable length, the following statement is used:
length = 15;
In each assignment statement above, there is a value on the right-hand side, and a variable name on the
left-hand side of the equal (“=”) symbol. The computer takes the value on the right-hand side of the
equal symbol and puts this value in the named memory location, on the left-hand side. The execution of
this statement is shown pictorially in Figure 2.3.
width = 10
10
stores 10 in width
memory location
3
After the two assignment statements are executed, a picture of memory is shown in Figure 2.4. It should
be noted that the area memory location does not contain a value since no assignment statement was
written to put a value in the corresponding variable.
width length
10 15
area
It is possible to put a new value in a memory location that already has a value by using another
assignment statement. For example, to put the value 20 in the width memory location, the following
statement can be used:
width = 20;
Since a memory location can store only one value at a time, the value stored is always the last one that
was put there.
It is often desirable in a computer program to display the value of a memory location so that it can be
viewed by humans (as well as by other programs). To display the value of a memory location on the
monitor, a cout statement can be used with the name of the corresponding variable. For example, to
display the value of the width memory location, the following statement is used:
4
When this statement is executed, the value of the width memory location (currently 20) is displayed on
the monitor. However, this is not too meaningful. A label should be displayed before the name of the
variable to indicate what data is being displayed. For example,
Note that each item of data to be displayed is separated by “<<”. The output generated by this
statement is as follows:
Similarly, to display the value stored in the length memory location, the following cout statement can
be used:
A complete program to declare the variables, assign 10 to the width variable, assign 15 to the length
variable, and then display the values stored in the width and length variables is given below:
#include <iostream>
int main () {
int width;
int length;
int area;
width = 10;
length = 15;
return 0;
}
5
In the next chapter, we will show how to assign a value to the area memory location by performing a
calculation based on the values stored in the width and length memory locations. This will solve the
problem of finding how much carpet is required to cover the room.
A variable name should be carefully chosen to give an indication of the data contained in the memory
location. It must also follow the rules of the programming language being used. Suppose we would like
to give a name to the memory location for storing the width of a room. A suitable variable name could
be “width”.
When giving a name to a variable in C++, the letters of the alphabet, digits, and the underscore
character (‘_’) can be used. The following rules apply:
• The variable name must be less than or equal to 1024 characters, the first of which must be a
letter; however, it is generally easier to work with short, meaningful names in a program.
• Letters, digits, and the underscore character can be combined in any way. No punctuation
characters, spaces or special symbols (such as the dollar sign and percent sign) are allowed.
• The name cannot be a keyword (a word that has a special meaning in a programming language).
For example, int cannot be used as a variable name, since it is a keyword having a special
meaning in C++.
Since each variable identifies a specific memory location, whenever the name of the variable is used, it
refers to the actual memory location. So, if the following is written, it means that the value 10 is being
stored in the memory location identified by the width variable:
width = 10;
This can be simplified by saying, “the value 10 is stored in the width variable”.
6
2.6 Floating Point Variables
Earlier in this chapter, we described how to declare and manipulate integer variables, i.e., variables
which store whole number quantities. However, a computer program must also be able to manipulate
fractional or floating-point numbers (numbers which have a “decimal” point). For example, a program
must be able to handle currency values such as 5000.25 or fractional values such as 0.5.
To declare a variable that will store a floating-point number, the keyword float is used. For example, to
declare a variable balance that will store a customer’s account balance in a bank program, the following
statement can be used:
float balance;
To assign a value to the balance variable, an assignment statement can be used, just as with integer
variables:
balance = 5000.25;
To display the value of a floating-point variable on the monitor, a cout statement can be used with the
name of the corresponding variable. For example,
If a floating-point number is too large to fit in a float variable, a double variable can be used. This kind of
variable is declared and used the same way as a float variable except that it is declared with the
keyword double. For example,
double balance;
So far, we have shown how numeric values such as integers and floating-point numbers can be stored
and manipulated by a computer program. However, it is also common for a program to use non-numeric
data. For example, it is often necessary to store a sequence of characters representing things such as a
7
person’s name, a person’s email address, the name of a country, etc. This can be done by using a string
memory location. A string memory location is declared in a similar manner to an integer or floating-
point memory location:
string firstName;
string lastName;
To assign a value to a string, the sequence of characters in the string must be enclosed in double
quotation marks. Single quotation marks will not work. In the following code, we assign values to the
firstName and lastName string variables and then display the value of the variables on the monitor in
the usual manner:
firstName = "John";
lastName = "Doe";
A typical program manipulates data from the real world to solve the problem at hand. This data can be
in the form of integer values, floating-point numbers, strings, or some other type. The program may
need to manipulate even more complex types of data such as images, audio, and video; however, these
data types are beyond the scope of this book.
The choice of variables in a program will depend on the real-world problem being solved and the type of
data involved. Once it is determined that a memory location is required, the next step is to determine
what type of quantity will be stored in that location, e.g., integer, floating-point number, or string. The
variable is then declared accordingly, e.g.,
int customerNumber;
float interestRate;
double balance;
string customerEmail;
8
2.8 Programming Style
Variable names make up a large part of the code in a computer program. It is good programming style
for the names of variables to correspond to the actual problem being solved. For example, if we are
writing a program to calculate the amount of carpet that is required to cover a room, good variable
names would be amount or area of carpet, length of room, and width of room. It would be
inappropriate to name the variables for the sides of the room as “john” or “value1”. The program will
still work with these variable names; however, it will make the program harder to read and understand.
It is possible to declare variables with very long names. However, given the amount of typing that is
required and the amount of space that it takes up on a line, it is generally easier to work with short,
meaningful names in a program.
In the real world, there are quantities that are named using two or more words. For example, a variable
for the “first name” or the “last name” of a person can be formulated using two words. When a variable
name comprises of two or more words, the words can be separated by an underscore character, e.g.,
string first_name;
string last_name;
int blood_pressure_meter_code;
Another approach is to join all the words together, writing the first letter of the first word in lowercase
and the first letter of each of the remaining words in uppercase, e.g.,
string firstName;
string lastName;
int bloodPressureMeterCode;
9
2.9 Exercises
1. Each of the following variable declarations contains an error. Find and correct each one.
(a) float 2dp; float dp2;
2. Each of the following sets of statements contain an error. Find and correct each one.
(a) string s;
string s;
s = 5;
s = "5"
3. Specify the type of data (int, float, string) that should be used to declare a variable in each of the
following cases.
(a) The name of a city string
(b) A URL string
(c) The age of a person int
(d) The number of persons on a flight int
(e) The price of an item in the supermarket float
(f) A customer’s telephone number string
10
4. Give the output of each of the following sets of statements.
(a) int a, b;
a = 5;
b = 10; 25
a = 25;
cout << a;
(b) int a, b, c;
a = 5;
nothing
b = 10;
cout << c;
(c) string a, b;
a = "one"; one
b = "two"; two
cout << a << endl;
cout << b << endl;
11