Data Structures - Arrays
Data Structures - Arrays
ARRAYS
2.1 Introduction
2.2 Types of Arrays
C
2.3 Representation of One-Dimensional Array in Memory h
2.4 Array Traversal
a
2.5 Insertion and Deletion
2.5.1 Insertion p
2.5.2 Deletion
t
2.6 Sorting and Searching
2.6.1 Sorting e
2.6.2 Searching
r
2.7 Representation of Multi-Dimensional Array in Memory
2.8 Realizing Matrices Using Two-Dimensional Arrays
2.9 Matrix Operations
O
2.9.1 Addition u
2.9.2 Subtraction
2.9.3 Multiplication
t
2.9.4 Transpose l
Solved Problems
i
Summary
Key Terms
n
Multiple-Choice Questions e
Review Questions
Programming Exercises
Answers to Multiple-Choice Questions
Arrays 2.1
2.1 INTRODUCTION
In Chapter 2, we briefly introduced one of the most important and commonly used derived data types,
called array. In this chapter, we will observe how array is used as a data structure in different programming
situations. We will also get familiar with the logical representation of arrays in memory.
An array is regarded as one of the most fundamental entities for storing logical groups of data. It
also forms the basis for implementing some advanced data structures, like stacks and queues, as we
shall see in the later chapters.
Typically, an array is defined as a collection of same type elements. That means, it can store a group
of integers, characters, strings, structures, and so on. However, an array cannot store different type
elements like a group of integers and fractions, or a group of strings and integers. Following are some
of the characteristics associated with arrays:
1. It uses a single name for referencing all the array elements. The differentiation between any two
elements is made on the basis of index value.
2. It stores the different elements at consecutive memory locations.
3. Its name can be used as a pointer to the first array element.
4. Its size is always a constant expression and not a variable.
5. It does not perform bound checking on its own. It has to be implemented programmatically.
Before we delve further into exploring array as a data structure, let us first identify the different
types of arrays.
The various instances of multi-dimensional arrays are two-dimensional (2D) array, three-dimensional
(3D) array, four-dimensional (4D) array, and so on. The choice of a particular multi-dimensional array
depends on the programming situation at hand. For instance, if we are required to realize a 3 ¥ 3 matrix
programmatically, then we can do so by declaring a two dimensional array, say M[3][3]. Here, each
dimension of the array M signifies the row and column of the matrix respectively. Multi-dimensional
arrays are covered in greater detail later in this chapter. For now, let us focus on implementing and
manipulating one-dimensional array.
As shown in Fig. 2.1, each array element is stored at consecutive memory locations, i.e., 6000, 6002,
6004, and so on. The location of the first element, i.e., 6000 is also referred as the base address of the array.
If we know the base address of an array, then we can find the location of its individual elements by
using a simple formula, which is
Address of A[k] = B + W * k
Here,
A[ ] is the array.
B is the base address, i.e., the address of the first element.
W is the word size or the size of an array element.
k is the index identifier.
For instance, the address of the third element of array arr stored at index location 2 would be
Address of arr[2] = 6000 + 2 * 2
= 6000 + 4
= 6004
Note The word size of a data type is decided by the programming language being used and the
hardware specifications.
Arrays 2.3
Printing array elements,
Searching an element in the array, Mind Jog
Sorting an array, and so on
Algorithm What is ‘array index out of bound’?
It is a runtime error that is encountered when a
Example 2.1 Write an algorithm to sequentially program tries to reference as address location
traverse an array. outside of the defined array limits.
traverse(arr[], size)
Step 1: Start
Step 2: Set i = 0
Step 3: Repeat Steps 4-5 while i < size
Step 4: Access arr[i]
Step 5: Set i = i + 1
Step 6: Stop
Program
Example 2.2 Write a C program to traverse each element of an array and print its value on the console.
Program 2.1 performs array traversal and prints the array elements as output. It uses the algorithm
depicted in Example 2.1.
Program 2.1 C program to traverse each element of an array and print its value
#include <stdio.h>
#include <conio.h>
printf(“Press any key to perform array traversal and display its elements:
\n\n”);
getch();
getch();
}
arr[0] = 2
arr[1] = 6
arr[2] = 7
arr[3] = 3
arr[4] = 8
Program analysis
void traverse(int*, int); Declares the prototype for the traverse() function for traversing
an array
traverse(arr,N); Calls the traverse() function for traversing the array arr
containing N elements
for(i=0;i<size;i++) Uses the for loop to access the array elements with each
iteration
Tip While traversing an array, the index identifier should be updated carefully so that array
out of bound situation does not arise. In this situation, the program tries to access a
location outside of the reserved memory block, which is an illegal operation.
Arrays 2.5
Fig. 2.2 Array insertion
Algorithm
void main()
{
int array[10] = {-1, 3, 5, 22, 77};
N = 5;
for(i=N;i>=k;i—)
array[i+1]=array[i];
The existing array elements need
array[k] = P; to be moved to make space for the
N = N + 1; new element.
getch();
}
Output
Arrays 2.7
Program analysis
for(i=N;i>=k;i—) Shuffles the array elements to the right to create space for inserting a
array[i+1]=array[i]; new element.
2.5.2 Deletion
The deletion of elements follows a similar procedure as insertion. The deletion of element from the
end is quite simple and can be achieved by mere updation of index identifier. However, to remove an
element from the middle, one must move all the elements present to the right of the point of deletion,
one position to the left. Figure 2.3 depicts the deletion of an element from an array.
Algorithm
void main()
{
int array[10] = {-1, 3, 5, 22, 77};
int i, k, N, D;
clrscr();
N = 5;
D = array[k];
for(i=k;i<=N-2;i++)
array[i]=array[i+1];
The existing array elements need
to be moved to fill the vacant space
N = N - 1; created by the deleted element.
getch();
}
Arrays 2.9
Output
The contents of the array are:
array[0] = -1
array[1] = 3
array[2] = 5
array[3] = 22
array[4] = 77
Enter the index location from where element is to be deleted:
3
22 element deleted from index location 3
The contents of the array after array deletion are:
array[0] = -1
array[1] = 3
array[2] = 5
array[3] = 77
Program analysis
Note For large-sized arrays, inserting an element at the middle could be a considerable
programming overhead as it would require the other elements to the moved from their
current positions.
Refer to Section 10.2.3 for the algorithm on applying bubble sorting technique to sort an array.
Program
void main()
{
int array[5]= {5, 4, 3, 2, 1};
int i, k, j, temp;
clrscr();
Arrays 2.11
{
/*Swapping adjacent elements*/
temp = array[j+1];
array[j+1] = array[j]; If the swap operation moves the
array[j] = temp; larger element towards the right then
} the array is sorted in ascending order,
otherwise it is sorted in descending
order.
printf(“\nThe sorted elements are:\n”);
for(i=0;i<5;i++)
printf(“array[%d] = %d\n”,i,array[i]); /*Printing sorted array*/
getch();
}
Output
The initial array elements are:
array[0] = 5
array[1] = 4
array[2] = 3
array[3] = 2
array[4] = 1
for(j=0;j<i-1;j++) Uses for loop to compare the array elements in each pass
of bubble sort algorithm
temp = array[j+1];
array[j+1] = array[j];
Note Just like an integer array, sorting can also be applied to an array of floats, characters,
structures, and so on.
Refer to Section 10.3.1 for the algorithm on applying linear search on an array.
Program
void main()
{
int array[5] = {22, 19, 4, 8, 10};
int i, flag, k, index;
clrscr();
flag = 0;
Arrays 2.13
printf(“\nEnter the element to be searched:\n”);
scanf(“%d”,&k);
if(flag==1)
printf(“Search is successful! Element %d is present at index location
%d in the array”,k,index);
else /*Successful Search*/
printf(“Unsuccessful Search!”);
getch();
}
Output
The contents of the array are:
array[0] = 22
array[1] = 19
array[2] = 4
array[3] = 8
array[4] = 10
Note Just like an integer array, searching can also be performed on an array of floats, characters,
structures, and so on.
As shown in Fig. 2.4, the elements of a two-dimensional array are stored at consecutive memory
locations. The only difference is in the order in which these elements are stored in memory. In column-
major order, the elements are stored column-by-column while in row-major order the elements are
stored row-by-row. Both these memory representations are intrinsic to a programming language and
the programmer does not have a choice of selecting a particular representation format for storing array
elements.
Arrays 2.15
The formula for computing the address location of a multi-dimensional array element in row major
implementation is given below:
Address of A[i,j] = B + W (n (i – LBR) + (j – LBC))
Here,
1. A[ ][ ] is the multidimensional array.
2. B is the base address.
3. W is the word size or the size of an array element.
4. n is the number of columns.
5. i, j are the index identifiers.
6. LBR is the lower bound of row index.
7. LBC is the lower bound of column index.
Similarly, the formula for computing the address location of a multi-dimensional array element in
column major implementation is given below:
Address of A[i,j] = B + W (m (j – LBC) + (i – LBR))
Here, m represents the number of rows.
Example 2.9 A 10 ¥ 12 matrix is
implemented using array A[10][12]. If the
Check Point
base address of the array is 200 and the word
1. What is row-major order?
size is 2 then compute the address of the element
Ans. It is the memory representation of a
A[4,7] in:
two-dimensional array in row-by-row fashion.
(a) Row major order
(b) Column major order 2. What is column-major order?
Assume that the lower bound of both row and Ans. It is the memory representation of a two-
column indices is 1. dimensional array in column-by-column fashion.
Check Point
1. What is matrix addition?
Ans. It is the task of adding the relative elements of two matrices.
2. What is matrix transpose?
Ans. It is the task of changing the rows into columns and columns into rows.
Solved Problems
Problem 2.1 Consider the following array of integers:
35 18 7 12 5 23 16 3 1
Create a snapshot of the above array for the following operations:
Inserting element 99 at index location 2.
Deleting the first element of the array.
Solution
Array contents after insertion: 35 18 99 7 12 5 23 16 3 1
Array contents after deletion: 18 7 12 5 23 16 3 1
Problem 2.5 A two-dimensional array A[5][10] is implemented in row order manner in the memory.
Deduce the address of the A[3][5] element, if the base address of the array is 3000 and the word size is
2. Assume the lower bound of row and column indices to be 1.
Solution Address of A[i,j] = B + W (n (i – LBR) + (j – LBC))
Address of A[3,5] = 3000 + 2 (10 (3 – 1) + (5 – 1))
= 3000 + 2 (24)
= 3048
Summary
Arrays are characterized as one-dimensional and multi-dimensional arrays.
One-dimensional arrays are stored at consecutive locations in memory.
Array traversal involves visiting the array elements and storing or retrieving values from it.
Insertion is the task of adding an element into an existing array while deletion is the task of
removing an element from the array.
Sorting involves arranging the elements of an array in a specific order or sequence.
Searching involves locating a specific element in an array.
Multi-dimensional array either stores the array elements in row major order or column major
order.
Two-dimensional arrays are most commonly used for realizing matrices.
Common operations performed on matrices are: addition, subtraction, multiplication, transpose.
Key Terms
Array An array is defined as a collection of same type elements, such as integers, characters,
strings, structures, and so on.
One-dimensional array It is a group of same type data elements, such as integers, floats, or
characters.
Multi-dimensional array It is a group of data elements, where each element is itself an array.
Array subscript It is the index identifier used to identify individual array elements.
Arrays 2.27
Base address It is the memory address of the first element of an array.
Sorting It involves arranging the elements of an array in a specific order or sequence.
Searching It involves locating a specific element in an array.
Row major order It is the memory representation of a two-dimensional array in row-by-row
fashion.
Column major order It is the memory representation of a two-dimensional array in column-
by-column fashion.
Multiple-Choice Questions
2.1 Which of the following is not true about arrays?
(a) It uses a single name for referencing all the array elements.
(b) Its name can be used as a pointer to the first array element.
(c) It performs automatic bound checking on its own.
(d) It stores the different elements at consecutive memory locations.
2.2 Which of the following is an incorrect array representation?
(a) {2, 5, 6, 1, 9}
(b) {2.5, 5.5, 6.8, 1.0, 9.7}
(c) {‘S’, ‘J’, 6, ‘4’, ‘P’}
(d) All of the above are correct
2.3 While performing array insertion, the elements to the right of the point of insertion are required
to be moved in which direction?
(a) Right
(b) Left
(c) They are not required to be moved
(d) None of the above
2.4 While performing array deletion, the elements to the right of the point of deletion are required
to be moved in which direction?
(a) Right
(b) Left
(c) They are not required to be moved
(d) None of the above
2.5 Which of the following is a representation of multi-dimensional array in memory?
(a) Row major order
(b) Column major order
(c) Sequential order
(d) Both (a) and (b)
2.6 Address of A[i,j] = B + W (m (j – LBC) + (i – LBR)) is the formula for computation of memory
addresses of which of the following array representations?
(a) Column major order
(b) Row major order
(c) Sequential order
(d) None of the above
Review Questions
2.1 What is an array? What are its various types?
2.2 Explain the representation of a one-dimensional array in memory with the help of an illustration.
2.3 What is array traversal? Why is it used?
2.4 What are the typical operations associated with arrays? Explain.
2.5 Write an algorithm for deleting an element at index location k in the array A[N].
2.6 What is the difference between sorting and searching?
2.7 Explain the representation of a two-dimensional array in memory with the help of an illustration.
2.8 Explain with the help of an illustration how a 2 ¥ 2 matrix is stored in memory using column
major order representation.
2.9 What is matrix multiplication? Explain with the help of an example.
2.10 What is the significance of transposing a matrix?
Programming Exercises
2.1 Write a C program to find the smallest element in an integer array.
2.2 Write a C program to read a value and insert it at the middle of an integer array.
2.3 Write a C program to sort an array of 10 integers.
2.4 Write a C program to demonstrate searching on an array of ten integers.
2.5 Write a C program to show how matrices are realized using two-dimensional arrays.
2.6 Write a C program to perform matrix subtraction.
2.7 Write a C program to perform transpose of a matrix.
2.1 (c) 2.2 (c) 2.3 (a) 2.4 (b) 2.5 (d)
2.6 (a) 2.7 (b) 2.8 (c)
Arrays 2.29