Data and Variables

All computer programs, except the most trivial, are written to operate on data. For example:

the data for an action game might be keys pressed or the position of the cursor when the mouse is clicked;

the data for a word processing program are the keys pressed while you are typing a letter;

the data for an accounting program would include, among other things, expenses and income;

the data for a program that teaches Spanish could be an English word that you type in response to a question.

For a program to be run, it must be stored in the computer’s memory. When data is supplied to a program, that data is also stored in memory. Thus we think of memory as a place for holding programs and data. One of the nice things about programming in a high-level language (like C or Java) is that you don’t have to worry about which memory locations are used to store your data. But how do we refer to an item of data, given that there may be many data items in memory?

Think of memory as a set of boxes (or storage locations). Each box can hold one item of data, for example, one number. We can give a name to a box, and we will be able to refer to that box by the given name. In our example, we will need two boxes, one to hold the side of the square and one to hold the area. We will call these boxes s and a, respectively.

If we wish, we can change the value in a box at any time; since the values can vary, s and a are called variable names, or simply variables. Thus a variable is a name associated with a particular memory location or, if you wish, it is a label for the memory location. We can speak of giving a variable a value, or setting a variable to a specific value, such as 1, for instance. Important points to remember are:

a box can hold only one value at a time; if we put in a new value, the old one is lost;

we must not assume that a box contains any value unless we specifically store a value in the box. In particular, we must not assume that the box contains 0.

Variables are a common feature of computer programs. It is very difficult to imagine what programming would be like without them. In everyday life, we often use variables. For example, we speak of an ‘address’. Here, ‘address’ is a variable whose value depends on the person under consideration. Other common variables are telephone number, name of school, subject, size of population, type of car, television model, etc. (What are some possible values of these variables?)

Now that we know a little bit about variables, we are ready to develop the algorithm for calculating the area of a square.