Module 4 - Arrays and Indexing Types
Module 4 - Arrays and Indexing Types
4.1 Introduction
An Array is a linear data structure that collects elements of the same data
type and stores them in contiguous and adjacent memory locations. A
Linear array is a list of a finite number n of homogeneous data elements
(i.e., data elements of the same data type) such that
(a) The elements of the array are referenced respectively by an index set
consisting of n consecutive numbers.
(b) The elements of the array are stored respectively in successive
memory locations.
Thus, an Array is a collection of variables of the same data types that are
referred to using a common name. An array has a name, size, index and
elements.
Page 1 of 19
(b) Arrays are best to process multiple values quickly and easily.
(c) Arrays are good for storing multiple values in a single variable. In
computer programming, most cases require storing a large amount of
data of a similar type. To store such an amount of data, we need to
define a large number of variables. It would be very difficult to
remember the names of all the variables while writing the programs.
Instead of naming all the variables with a different name, it is better to
define an array and store all the elements into it.
(d) Arrays provide O(1) random access lookup time. That means,
accessing the 1st index of the array and the 1000th index of the array
will both take the same time. This is due to the fact that array comes
with a pointer and an offset value. The pointer points to the right
location of the memory and the offset value shows how far to look in
the said memory.
Page 2 of 19
The difference between an array index and a memory address is that the
array index acts like a key value to label the elements in the array. However,
a memory address is the starting address of free memory available.
The Figure 4.2 above shown the memory allocation of an array “arr” of size
5. The array follows a 0-based indexing approach. The base address of the
array is 100 bytes. It is the address of arr[0]. Here, the size of the data type
used is 4 bytes; therefore, each element will take 4 bytes in the memory.
Let Arr be a linear array in the memory of the computer. The following
information given below to access any random element from the array:
Page 3 of 19
LOC (Arr[k]) = address of element Arr[k] of the array Arr.
Since the elements of Arr are stored in the successive memory cells.
Accordingly, the computer does not need to keep track of the address of
every element of Arr array but needs to keep track only of the address of the
first element of Arr array denoted by Base (Arr) of array, the base address of
Arr array. Using base address, the computer calculates the address of any
element of Arr array by the following formula:
Here, size represents the memory taken by the primitive data types. As an
instance, int takes 2 bytes, float takes 4 bytes of memory space in C++.
For example, Suppose an array, Arr[-10 . . .+2 ] having Base address (BA) =
999 and size of an element = 2 bytes, find the location of A[-1].
Loc(Arr[-1]) = 999 + 2 x [(-1) - (-10)]
= 999 + 18
= 1017
Length= UB – LB + 1
Where UB is the largest index, called the upper bound, and LB is the
smallest index, called the lower bound. Note that length = UB when LB = 1.
Page 4 of 19
4.5 Type of Arrays
Array can be classified based on its dimensions and as static and dynamic
array.
Page 5 of 19
int a[size1][size2][size3]
Page 6 of 19
e.g.
Int a[10];
4.7.1 Traversal
Traversal is a process of processing or visiting each element in the array
exactly once. Let A be an array stored in the computer’s memory. If we want
to display the contents of A, it has to be traversed i.e., by accessing and
processing each element of A exactly once. The algorithm for Traversal is
shown below:
TRAVERSAL(LA, LB,UB, K)
[Here LA is a Linear array with lower boundary LB and upper
boundary UB. This algorithm traverses LA applying an operation
Process to each element of LA].
Page 7 of 19
Step 5. Exit.
The alternate algorithm for traversing (using for loop) is:
4.7.2 Insertion
Insert operation insert one or more data elements into an array. Based on
the requirement, a new element can be added at the beginning, end, or at
any given index of the array. Let A be a collection of data elements in the
memory of the computer. "Inserting" refers to the operation of adding
another element to the collection A. Inserting an element at the "end" of a
linear array can be easily done provided the memory space allocated for the
array is large enough to accommodate the additional element. On the other
hand, suppose we need to insert an element in the middle of the array.
Then, on the average, half of the elements must be moved downward to new
locations to accommodate the new location and keep the order of the other
elements. The algorithm for Inserting.
4.7.3 Deletion
Deletion refers to removing an existing element from the array and re-
organizing all elements of an array. Let A be a collection of data elements in
Page 8 of 19
the memory of the computer. "Deleting" refers to, the operation of removing
one of the elements from A. Deleting an element at the "end" of an array
presents no difficulties, but deleting an element somewhere in the middle of
the array would require that each subsequent element be moved one
location upward in order to "fill up" the array.
4.7.4 Search
The process of finding a particular element of an array is called Searching. If
the item is not present in the array, then the search is unsuccessful. A
search can be performed on an array element based on its value or its index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer
such that K<=N. the algorithm to find an element with a value of ITEM using
sequential search.
SEARCH
Step 1. Start
Step 2. Set J=0
Step 3. Repeat steps 4 and 5 while J < N
Step 4. IF LA[J] is equal ITEM THEN GOTO STEP 6
Step 5. Set J = J +1
Step 6. PRINT J, ITEM
7. Stop
4.7.5 Update
Update operation refers to updating an existing element from the array at a
given index.
Page 9 of 19
Algorithm
Consider LA is a linear array with N elements and K is a positive integer
such that K<=N. The algorithm updates an element available at the Kth
position of LA.
UPDATE
Step 1. Start
Step 2. Set LA[K-1] = ITEM
Step 3. Stop
4.7.6 Merging
Merging two arrays means combining two separate arrays into one single
array. For instance, if the first array consists of 3 elements and the second
array consists of 5 elements then the resulting array consists of 8 elements.
This resulting array is known as a merged array.
Algorithm:
MERGING
Step 1: Start
Step2: Create an array of size m+n named nums3[].
Step 3: Copy all elements of nums1[] to nums3[].
Step 4: Now traverse the elements of nums2[] and insert elements one
by one to nums3[]
Step 5: Stop
Page 10 of 19
(b) Traversing an array is a very simple process; we just need to
increment the base address of the array in order to visit each element
one by one.
(c) Any element in the array can be directly accessed by using the index.
The disadvantages of Arrays are:
(a) Array is homogenous. It means that the elements with similar data
type can be stored in it.
(b) In array, there is static memory allocation that is size of an array
cannot be altered.
(c) There will be wastage of memory if we store a smaller number of
elements than the declared size.
Page 11 of 19
// declare and initialize and array
int x[6] = {19, 10, 8, 17, 9, 15};
Here, the array x has a size of 6. However, we have initialized it with only 3
elements. In such cases, the compiler assigns random values to the
remaining places. Oftentimes, this random value is simply 0.
Page 12 of 19
4.10.4 Access Elements in C++ Array
In C++, each element in an array is associated with a number. The number
is known as an array index. We can access elements of an array by using
those indices.
// syntax to access array elements
array[index];
e.g. balance [4] = 50.0;
Page 13 of 19
Java arrays can store elements of any data type, including primitive types
such as int, double, and boolean, as well as object types such as String and
Integer. Arrays can also be multi-dimensional, meaning that they can have
multiple rows and columns. Arrays in Java are commonly used to store
collections of data, such as a list of numbers, a set of strings, or a series of
objects. By using arrays, we can access and manipulate collections of data
more efficiently than using individual variables.
dataType[] arrayName;
or
dataType arrayName[];
dataType can be primitive data types like int, char, double, byte, etc. or Java
objects and arrayName must be an identifier. The following code snippets
are examples of this syntax:
The above statement does two things; It creates an array using new
dataType[arraySize] and it assigns the reference of the newly created array
to the variable arrayRefVar.
Page 14 of 19
dataType[] arrayRefVar = new dataType[arraySize];
the statement below declares an array variable and myList, creates an array
of 10 elements of double type and assigns its reference to myList:
Here, we have created an array named age and initialized it with the values
inside the curly brackets. Other examples are:
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
Page 15 of 19
// access each array elements
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
When processing array elements, we often use either for loop or foreach loop
because all of the elements in an array are of the same type and the size of
the array is known. The examples below illustrate on how loop with arrays.
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
Page 16 of 19
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
You can invoke it by passing an array. For example, the following statement
invokes the printArray method to display 3, 1, 2, 6, 4, and 2.
Page 17 of 19
A method may also return an array. For example, the following method
returns an array that is the reversal of another array:
Page 18 of 19
(c) Write an Algorithm to count the even number of elements in a given
array of integers. Implement the algorithm using either C++ or Java.
(d) Write an Algorithm to check whether a given array of integers contains
5's and 7's. Implement the algorithm using either C++ or Java.
(e) Write an Algorithm to count the numbers of odd and even in an array.
Implement the algorithm using either C++ or Java.
Page 19 of 19