8. The Type int
So far, we have been using the word double
to introduce new variables. This word actually describes the range of possible values that the introduced variable is able to contain.[*] Until now, our variables have been allowed to contain any real numbers, including the positive and negative ones, with and without decimal fractions.
The word double
stands for: double precision floating point number. The double precision floating point numbers are accurate to approximately 15 decimal digits. The type float
is used for single precision floating point numbers, and it is accurate to approximately seven decimal digits.
This time, we are going to discuss variables that can assume values only from a more limited set. A type of variable that is able to contain only integers will be discussed. To introduce such a variable, we might write:
int x = 7;
The word int
comes
from the word "integer". An integer is a whole number; it can be
positive, negative, or equal to 0.
But, why would we want to restrict a
variable to integers in the first place? Are the variables of type double
not more
versatile?
Although it might seem strange, the answer
is negative. There are some things that only the variables of type int
can do,
that cannot be done with the variables of type double
. For
example, for every variable of type int
we might ask whether its value is
odd or even, while for the variables of type double
this question generally makes
no sense. For example, is the number 3.232 odd or even? The question makes no
sense and we might need to rephrase our question as whether this value is odd,
or even, or something else.
There is a vast range of objects in the
natural world that we are used to think of in terms of whole numbers. For
example, an answer to the question "How many (glasses, boxes, people) are
there in a room?" will understandably be formulated in terms of whole
numbers, since the objects in question are by definition non divisible. It goes
beyond saying that the sentence "There are 3.4 people in this room"
does not make any sense, unless the person uttering it intended to be humorous
in a rather grotesque manner. Since counting problems are quite common in
programming, the type int
will find its deserved place in our programs, beginning with the following chapter.