Page 79 - PowerPoint Presentation
P. 79
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology DCIT 25 – Data Structures and Algorithms
Week 5: Arrays
Objectives: After the completion of the chapter, students will be able to:
Learn the concept of Array and Multidimensional Array
Learn the structure of Array and Multidimensional Array
Declare and Array and Multidimensional Array
An Array is a way to reference a series of memory locations using the same name.
Each memory location is represented by an array element.
An Array Element is similar to one variable except it is identified by an index value
instead of a name. An index value is a number used to identify an array element.
Now, let’s see what an array looks like, with the three array elements shown next. The
array is called grades. The first array element is called grades[0]. The zero is the index value.
The square bracket tells the computer that the value inside the square bracket is an index.
grades[0]
grade[1]
grade[2]
Each array element is like a variable name. For example, the following variables are
equivalent to array elements. There is no difference between array elements and variables –
well, almost no difference, but we’ll get to the difference in a moment. For now, let’s explore
how they are the same. Here are three integer variables:
int MaryGrade;
int BobGrade;
int AmberGrade;
You probably recall from your programming class that you store a value into a
memory location by using an assignment statement. Here are two assignment statements.
The first assigns a value to a variable, and the other assigns a value to an array element.
Notice that these statements are practically the same except reference is made to the index
of the array element in the second statement:
int grades[1]; / variable initialization
MaryGrade = 90; / value declaration
grades[0] = 90; / value declaration
Suppose you want to use the value stored in a memory location. There are a number
of ways to this in a program, but a common way is to use another assignment statement like
the ones shown in the next example. The first assignment statement uses two variables, the
next assignment statement uses two array elements, and the last assignment statement
assigns the value referenced by a variable name and assigns that value to an array element:
BobGrade = MaryGrade;
grades[0] = grades[1];
grades[0] = BobGrade;
You’ve probably noticed a pattern developing. You use an array element the same
way you use a variable.
Why an Array?
There are two important differences between an array element and a variable, and
those difference makes working with large amounts of data a breeze. Suppose you had to
work with 100 grades to calculate the average grade. How would you do this?
The challenge isn’t applying the formula for calculating the average. You know how
that’s done. The challenge is to come up with 100 variable names and then reference all those
variable names in a program.
Page | 26