Saturday, 27 April 2013

Variables and Data Types.

The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write
several lines of code, compile them, and then execute the resulting program just to obtain a simple sentence
written on the screen as result. It certainly would have been much faster to type the output sentence by ourselves.
However, programming is not limited only to printing simple texts on the screen. In order to go a little further on
and to become able to write programs that perform useful tasks that really save us work we need to introduce the
concept of variable.
Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to memorize also
the number 2 at the same time. You have just stored two different values in your memory. Now, if I ask you to add
1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Values
that we could now for example subtract and obtain 4 as result.
The whole process that you have just done with your mental memory is a simile of what a computer can do with
two variables. The same process can be expressed in C++ with the following instruction set:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Obviously, this is a very simple example since we have only used two small integer values, but consider that your
computer can store millions of numbers like these at the same time and conduct sophisticated mathematical
operations with them.
Therefore, we can define a variable as a portion of memory to store a determined value.
Each variable needs an identifier that distinguishes it from the others, for example, in the previous code the
variable identifiers were a, b and result, but we could have called the variables any names we wanted to invent,
as long as they were valid identifiers.

No comments:

Post a Comment