Page 80 - PowerPoint Presentation
P. 80
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology DCIT 25 – Data Structures and Algorithms
First, you need to sum all the grades by writing a statement similar to the following.
(We’ll stop at three variables because it’s difficult to identify 100 variables).
sum = MaryGrade + BobGrade + AmberGrade
Now, here’s how a smart programmer meets this challenge using an array:
sum = 0;
for (int i=0; i<100; i++) {
sum = sum + grades[i];
}
The control variable of the for loop is the index for the array element, enabling the
program to quickly walk through all array elements in three lines of code. (The first statement
has nothing to do with walking through all the array elements. It only initializes the sum
variable with the total grades.)
The other difference between an array and a variable is that all the array elements are
next to each other in memory. Variables can be anywhere in memory. For example, grades[0]
is next to grades[1] in memory, grades[1] is next to grades[2] in memory, and so on. In
contrast, MaryGrade and BobGrade variables can be anywhere in memory, even if they are
declared in the same declaration statement.
Arrays and Data Structure
Some programmers might say that arrays are the backbone of data structure because
an array enables a programmer to easily reorganize hundreds of values stored in memory by
using an array of pointers to pointers.
This is a mouthful to say, so we drew a picture to show you the importance of arrays
in data structures. The figure below shows memory, each block is a byte. We’ll say that two
bytes are needed to store a memory address in memory. You need to store a memory address
in memory because you will use it to refer to other memory addresses.
Elements of an array stored sequentially in memory
First, create an array called letters and assign characters to it, as shown here:
char letters[3];
letters[0] = ‘C’;
letters[1] = ‘B’;
letters[2] = ‘A’;
You will notice in figure above that each letter appears one after the other in memory.
This is because these values are assigned to elements of an array, and each array element
is placed sequentially in memory.
Next create an array of pointers. As you’ll recall from the last chapter, a pointer is a
variable that contains a memory address of another variable. In this example, you will use an
array of pointers instead of a pointer variable.
Page | 27