Page 82 - PowerPoint Presentation
P. 82
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology DCIT 25 – Data Structures and Algorithms
the array when the array is declared. There are four components of a statement that declares
an array. These components are a data type, an array name, the total number of array element
to create (or what we call array size), and a semicolon (;). Here’s the declaration statement in
C and C++:
int grades[10];
The Data Type is a keyword that tells the computer the amount of memory to reserve
for each element of the array. In this example, the compiler to told to reserve enough memory
to store an integer for each array element.
The Array Name is the name you use within a program to reference an array element.
The array name in this example is grades. The number within the square brackets is the total
number of elements that will be in the array. The previous statements tell the computer to
create an array of 10 elements.
Avoid making a common rookie mistake, previously in this chapter, we learned that the
index for the first array element is zero, not one. Therefore, the tenth array element has the
index value 9, not 10.
Some programs confuse an index with the total number of array elements. That is,
they use the value 9 within the square brackets when declaring an array because they
assume, they are declaring 10 elements. But in reality, they are declaring an array of 9
elements.
Multidimensional Arrays
The array described in this chapter is referred to as one-dimensional array because
the array consists of one series of elements However, an array can have more than one series
of elements. This is called a Multidimensional Array.
A multidimensional array consists of two or more arrays defined by sets of arrays
elements, as shown in the figure below. Each set of array elements is an array. The first set
of array element is considered as the primary array, and the second and subsequent sets of
array elements are considered subarrays.
There are two arrays in the multidimensional array shown in the figure below. Each
element of the first array points to a corresponding array.
Although you can create an array with any size multidimension, many programmers
limit an array to two dimensions only. Any size greater than two dimension becomes unwieldy
to manage.
An analogy we find helpful is visualizing a table (rows and columns) for a two-
dimensional array and a cube for a three-dimensional array.
Why use a Multidimensional Array?
A multidimensional array can be useful to organize subgroups of data within an array.
Let’s say that a student has three grades, a mid-term grade, a final exam grade and a final
grade. You can store all three grades for an endless number of students in a two-dimensional
array, as shown in the figure below:
Page | 29