Next: Arrays in C++
Up: Introduction to C++ Programming
Previous: Exercises
Variables in a program have values associated with them. During program execution these values are accessed by using the identifier associated with the variable in expressions etc. In none of the programs written so far have very many variables been used to represent the values that were required. Thus even though programs have been written that could handle large lists of numbers it has not been necessary to use a separate identifier for each number in the list. This is because in all these programs it has never been necessary to keep a note of each number individually for later processing. For example in summing the numbers in a list only one variable was used to hold the current entered number which was added to the accumulated sum and was then overwritten by the next number entered. If that value was required again later in the program there would be no way of accessing it because the value has now been overwritten by the later input.
If only a few values were involved a different identifier could be declared for each variable, but now a loop could not be used to enter the values. Using a loop and assuming that after a value has been entered and used no further use will be made of it allows the following code to be written. This code enters six numbers and outputs their sum:
sum = 0.0; for (i = 0; i < 6; i++) { cin >> x; sum += x; }
This of course is easily extended to n
values where n
can be as large as required. However if it was required to access the
values later the above would not be suitable. It would be possible to
do it as follows by setting up six individual variables:
float a, b, c, d, e, f;
and then handling each value individually as follows:sum = 0; cin >> a; sum += a; cin >> b; sum += b; cin >> c; sum += c; cin >> d; sum += d; cin >> e; sum += e; cin >> f; sum += f;which is obviously a very tedious way to program. To extend this solution so that it would work with more than six values then more declarations would have to be added, extra assignment statements added and the program re-compiled. If there were 10000 values imagine the tedium of typing the program (and making up variable names and remembering which is which)!
To get round this difficulty all high-level programming languages use the concept of a data structure called an Array