MODULE 4: ARRAYS
AND INDEXING TYPES
SUB-GROUP 2
COSC 302
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.
PROPERTIES OF ARRAY
• Each element in an array is of the same data type and carries the same
size.
• Elements in the array are stored at contiguous memory locations from
which the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate
the address of each element of the array with the given base address and
the size of the data element.
THE NEED FOR ARRAYS
• Sorting and searching a value in an array is easier.
• Arrays are best to process multiple values quickly and easily.
• 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.
• 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.
INDEXING TYPES AND
MEMORY REPRESENTATION
• Element: Each item stored in an array is called an element. Elements of
an array may be denoted by subscript notation a1, a2, a3 . . . an.
• Index: Each location of an element in an array has a numerical index,
which is used to identify the element.
LENGTH VS SIZE OF AN
ARRAY
• The length or size of an array refers to the total number of elements it
contains.
• If not explicitly stated, arrays are assumed to be indexed starting from 1
up to n.
• The formula to compute the length of an array: Length = UB - LB + 1,
where:
• - UB (Upper Bound): largest index in the array.
• - LB (Lower Bound): smallest index in the array.
• If the lower bound is 1, then Length = UB.
TYPES OF ARRAY
• Arrays can be classified based on their dimensions (rank) or their
allocation (static vs dynamic).
• Rank/Dimension of an Array:
• 1. One-dimensional Array: Arranged linearly. Declared as: int
arr[max_columns]; e.g., int a[10];
• 2. Two-dimensional Array: Organized in rows and columns (matrix).
Declared as: int arr[max_rows][max_columns]; e.g., int arr[5][5];
• 3. Multi-dimensional Array: Arrays with more than two dimensions (e.g.,
3D). Declared as: int a[size1][size2][size3]; e.g., int a[5][5][5];
STATIC VS DYNAMIC ARRAYS
• Static Arrays:
• - Fixed size determined at compile-time.
• - Stored on the stack and deleted when out of scope.
• - Cannot change size after creation.
• - May contain default or garbage values if uninitialized.
• Dynamic Arrays:
• - Size can change at run-time.
• - Stored on the heap.
• - Allow adding and removing elements during execution.
• - Managed using language features or libraries.
MANIPULATING THE
CONTENTS OF AN ARRAY
• Arrays support several fundamental operations:
• ✔ Traversal – Visit each element exactly once.
• ✔ Insertion – Add an element at a specified index.
• ✔ Deletion – Remove an element from a specified index.
• ✔ Search – Find an element by index or value.
• ✔ Sorting – Arrange elements in ascending or descending order.
• ✔ Update – Modify the value of an element at a given index.
• ✔ Merging – Combine two arrays into one.
TRAVERSAL OF AN ARRAY
• Traversal involves visiting and processing every element of the array.
• Algorithm 1: Using a while loop
• Step 1: Set K ← LB
• Step 2: Repeat while K ≤ UB:
• - Process LA[K]
• -K←K+1
• Step 3: Exit
• Algorithm 2: Using a for loop
• Step 1: For K = LB to UB:
• - Process LA[K]
• Step 2: Exit
MANIPULATING THE
CONTENT OF ARRAY (ARRAYS
OPERATIONS)
• The basic operations performed by an Arrays are:
• Traversal: print all the array elements one by one.
• Insertion: Adds an element at the given index.
• Deletion: Deletes an element at the given index.
• Search: Searches an element using the given index or by the value.
• Sorting: Arranging the elements of an Array in an order either in
ascending or descending order.
• Update: Updates an element at the given index.
• Merging: Combining the contents of two Arrays
COMPLEXITY OF ARRAY
OPERATIONS
Operation Average Case Worst Case
Access/Traversal O (1) O (1)
Search O(n) O(n)
Insertion O(n) O(n)
Deletion O(n) O(n)
In array, space complexity for worst case is O(n).
ADVANTAGES AND
DISADVANTAGES OF ARRAYS
• The advantages of Arrays are:
• Array provides the single name for the group of variables of the same
type. Therefore, it is easy to remember the name of all the elements of an
array.
• 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.
• Any element in the array can be directly accessed by using the index.
The disadvantages of Arrays are:
• Array is homogenous. It means that the elements with similar data type
can be stored in it.
• In array, there is static memory allocation that is size of an array cannot
be altered.
ARRAY IMPLEMENTATION IN
C++
• An array in C++ is a collection of elements of the same data type stored
in contiguous memory locations, where each element is accessed using
an index.
• It is useful for managing multiple related data items and can perform
various operations like sorting, searching, insertion, deletion, traversal,
and updating efficiently and effectively
ARRAY INITIALIZATION IN C+
+
• Array initialization involves assigning elements into memory locations within
an array. This can be done during declaration by using curly braces {}:
int x[6] = {19, 10, 8, 17, 9, 15};
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
• In cases where the exact size of the array is not known, we can carry out an
Implicit Size Inference:
int x[] = {19, 10, 8};
ARRAY DECLARATION IN C++
• To declare an array in C++ we use this syntax:
dataType arrayName[arraySize];
When declared in this way, it is called a single-dimensional array, which can be
viewed as a linear sequence of elements. Other types of arrays include:
ii) Two- dimensional
iii) Multi-dimensional
EMPTY MEMBERS C++
ARRAYS
• In situations where we store less elements than the than the specified
array size, the compiler would assign random values to the remaining
memory spaces. These values are either random or simply 0.
ACCESS ELEMENTS IN C++ AND
ARRAY IMPLEMENTATION IN JAVA.
• Accessing Elements in C++ Arrays
• In C++, arrays use zero-based indexing (first element is at index 0).
• You access elements with the syntax:
array[index]
E.g., balance[4] = 50.0; sets the fifth element to 50.
• You can read or modify array values using these indices.
• 2D arrays follow a row-column format:
matrix[1][2] accesses the value in the 2nd row, 3rd column.
EXAMPLE:
int numbers[5] = {7, 5, 6, 12, 35};
cout << numbers[2]; // Outputs 6
ARRAYS IN JAVA &
DECLARATION
• In Java, arrays are objects and hold fixed-size sequences.
• Declaring a Java array:
• int[] myList; // Preferred
• int myList[]; // Also valid
• To create the array:
• myList = new int[10]; // Creates an array of size 10
• Java arrays support both primitive types(e.g, int, double) and objects (e.g., string, integer).
• Arrays are zero-indexed: first element is at index 0.
• Example:
• String[] cars = {"Volvo", "BMW", "Ford"};
• System.out.println(cars[0]); // prints Volvo
JAVA ARRAYS - DETAILED
EXPLANATION
• Creating Arrays in Java
• Arrays in Java are created using the 'new' keyword.
Arrays are objects and must be declared and instantiated.
Syntax:
dataType[] arrayName = new dataType[arraySize];
Example:
int[] numbers = new int[5];
INITIALIZING ARRAYS IN JAVA
• Arrays can be initialized in two ways:
1. Using new keyword (then set values):
int[] scores = new int[3];
scores[0] = 90;
scores[1] = 85;
2. Direct initialization:
int[] scores = {90, 85, 100};
ARRAY LENGTH IN JAVA
• Java arrays have a built-in '.length' property that returns the array size.
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length); // Output: 4
ACCESSING ARRAY
ELEMENTS IN JAVA
• Access elements using index notation. Index starts from 0.
Syntax:
arrayName[index];
Example:
int[] age = {12, 4, 5, 2, 5};
System.out.println(age[0]); // prints 12
age[1] = 100; // updates second element
PROCESSING ARRAY
ELEMENT WITH FOR LOOP
• An array is a collection of values of the same type, stored together in
memory, and accessed using an index.
• "Arrays help us store multiple related values like scores or temperatures
in a single variable, using indexes like lockers."
• JDK 1.5 introduced a new for loop known as foreach loop or enhanced for
loop, which enables you to traverse the complete array sequentially
without using an index variable. The following codes displays all the
elements in the array myList:
• Firstly;
THE TRADITIONAL FOR LOOP
You Can use a for loop to process each element
Example:
For(int I =0; i<age.length; i++) {
System .out.println(age[i]);
}
THE FOR LOOP (FOREACH)
Syntax:
For(datatype item : arrayName){
System.out.println(items);
}
"The foreach loop lets us go through each element in the array without
using an index — making the code cleaner and safer."
PASSING ARRAYS TO
METHODS IN JAVA
• Just like you can pass a single value (like int x = 5) to a method, you can
also pass an entire array to a method — allowing you to reuse code and
handle large sets of data more easily.
• FOR EXAMPLE:
• public static void printArray(int[] array) {
• for (int i = 0; i < array.length; i++) {
• System.out.print(array[i] + " ");
• }
• }
• "This method named printArray accepts an integer array as its parameter
and prints each element using a for loop."
WE CAN INVOKE IT BY
PASSING AN ARRAY:
• printArray(new int[]{3, 1, 2, 6, 4, 2});
"Here, we’re creating a new array on the spot using new int[] and passing
it directly into the method."
RETURNING AN ARRAY FROM
A METHOD
• A method may also return an array. For example, the following method returns an array that is
the reversal of another array:
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
This method receives an array called list.
It creates a new array called result to store the reversed version.
Using a loop, it copies elements from front to back and back to front at the same time.
Finally, the reversed array is returned to the caller.