Array
Array
by
Farhan Sufyan
Contents
Arrays
1.1 Arrays
• An array is a collection of homogeneous or similar type of data items called elements of an array.
• The elements of an array is stored at contiguous memory locations.
• The elements of an array may be like char, int, float etc.
1
1.2 Need of Arrays
• Arrays are best for storing multiple values in a single variable.
• Arrays are better at processing many values easily and quickly.
• Sorting and Searching the values is easier in arrays.
• In Figure ??, we have shown the memory allocation of an array arr of size 5.
2
• The array follows 0-based indexing approach. The base address of the array is 100th byte. This will be the
address of arr[0].
• Here, the size of int is 4 bytes therefore each element will take 4 bytes in the memory.
3
1.9 Types of Arrays
• Array can be single dimensional or multi-dimensional.
• Accessing its elements involves a single subscript which can either represent a row or column index.
• Syntax for declaration of 1-D array in C:
– DataType ArrayName[Size];
– eg: int arr[5];
– Data type is the type of the elements of the array i.e. int, float, char etc;
– Array name is the valid C identifier.
– Size is the number of elements stored in array, it must be a positive integer.
• When the array is declared, the compiler allocates space in memory sufficient to hold all the elements of the
array, so the size of array should be known at the compile time.
4
1.10.1 1-D Array Declaration
1.10.1.1 Array declaration by specifying size
• Array declaration by specifying size:
int arr[10];
int n = 10;
int arr[n];
int arr[n];
int n = 10; // Invalid Declaration
int arr[4];
arr[0]=10, arr[1]=20, arr[2]=30, arr[3]=40;
• Compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements
as 0. Hence, if during the initialization the number of initializers are less than the size of array, then all the
remaining elements are assigned value zero.
• The above declaration is same as
5
• Another method of assigning value
int arr[2];
arr[0] = 5;
arr[3 / 2] = 2; // this is same as arr[1] = 2
#include <stdio.h>
void main(){
// Array declaration by initializing it with more elements than specified size.
int arr[2] = {10, 20, 30, 40, 50};
}
• No Index Out of bound Checking: There is no index out of bounds checking in C/C++. For example, the
following program compiles fine but may produce unexpected output when run.
#include <stdio.h>
void main(){
int arr[2];
printf("%d", arr[3]);
printf("%d", arr[-2]);
}
• We can’t copy all the elements of array to another array by simply assigning it to the other array. For example:
6
1.10.2 Accessing 1-D Array Elements
int a[5];
i = 2;
scanf("%d", &a[i]); //input value a[2]
printf("%d", &a[i]); //print value a[2]
printf("%d", &a[i++]); //print value a[2] and increment the value of i
int a[5];
upper index or bound = 4
lower index or bound = 0
Length of an Array = (4 - 0) + 1 = 5
Size of an Array (in Bytes) = Length of an Array x Size of array base type
int a[5];
Length of an array = 5
size of base data type = 4 (int 4 bytes)
Size of an Array (in Bytes) = 5 x 4 = 20 bytes
Address of any element of a 1D array can be calculated by using the following formula:
Byte address of element A[i] = Base Address + Size (base data type) * ( i - First Index)
Example:
int a[5];
Base or starting address (BA) = 2000
Size(S) = 4 (int 4 bytes)
Address of a[5] = BA x S(i - 0) = 2000 x 4(5-0) = 2020
Example: In an array, A[-10 ..... +2 ], Base Address (BA) = 999, Size of base data type or an element = 2 bytes.
Find the address of A[-1].
7
1.10.3 Traversal Operation on 1-D array
#include <stdio.h>
void main() {
int a[] = {1,3,5,7,8};
int n = 5,i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("a[%d] = %d, ", i, a[i]);
}
printf("\n");
}
8
1.10.4 Insertion Operations on 1-D array
• Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element
can be added at the beginning, end, or any given index of array.
• Following can be a situation with array insertion
– Input size and elements in array. Store it in some variable say size and arr.
– Input new element and position to insert in array. Store it in some variable say num and pos.
– To insert new element in array, shift elements from the given insert position to one position right. Hence,
run a loop in descending order from size to pos to insert. The loop structure should look like for(i=size;
i>=pos; i–).
– Inside the loop copy previous element to current element by arr[i] = arr[i - 1];
– Finally, after performing shift operation. Copy the new element at its specified position i.e. arr[pos -
1] = num;
#include <stdio.h>
void main() {
int a[5];
int size = 5,i;
printf("Please enter %d elemnts of the array: \n",size);
for(i = 0; i<size; i++) {
scanf("%d",&a[i]);
}
}
9
1.10.4.2 Inserting the Element at the Specific Location of Array
#include <stdio.h>
#define MAX_SIZE 100
void main()
{
int arr[MAX_SIZE];
int i, size, num, pos;
10
1.10.4.3 Inserting the Element at the First Position of an Array
• Remove the code that is asking the position of insertion from the user.
• Remove the code checking for valid position.
• Replace arr[pos-1] = num with arr[0] = num;
11
1.10.5 Time Complexity for Array insertion
1.10.5.1 When maintaining given order of elements
• At the beginning: O(n)
• At the end: O(1)
• At the specified location: O(n)
12
1.10.6 Deletion Operation on 1-D array
• Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
• Following can be a situation with array deletion:
1.10.6.1 Deletion of the Element at the Specific Location of Array (while maintaining order)
Step by step descriptive logic to remove element from array.
• Move to the specified location which you want to remove in given array.
• Copy the next element to the current element of array. Which is you need to perform array[i] = array[i + 1].
• Repeat above steps till last element of array.
• Finally decrement the size of array by one.
#include <stdio.h>
#define MAX_SIZE 100
void main()
{
int arr[MAX_SIZE];
int i, size, pos;
13
/* Invalid delete position */
while(pos <= 0 || pos > size){
printf("Invalid position! Please enter position between 1 to %d: ", size);
scanf("%d", &pos);
}
14
1.10.7.2 while not maintaining the given order
• At the beginning: O(1)
• At the end: O(1)
• At the specified location: O(1)
15
1.10.8 Updation Operation on 1-D array
• Update operation refers to updating an existing element from the array at a given index.
#include <stdio.h>
void main()
{
int arr[MAX_SIZE];
int i, size, pos, item;
16
1.10.9 Home Assignment of 1-D array
• Write a C program to copy all elements from an array to another array.
• Write a C program to find sum of all array elements.
• Write a C program to find maximum and minimum element in an integer array.
• https://www.youtube.com/watch?v=Bnjbun-hiBk&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU&
index=2
• https://www.youtube.com/watch?v=CMbpZK_xqoc&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU&
index=3
17
1.11 Multi-Dimensional Array
• In C/C++, we can define multidimensional arrays in simple words as array of arrays.
• Total number of elements that can be stored in a multidimensional array can be calculated by multiplying
the size of all the dimensions.
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
18
1.11.1 2-D Array
• Two-dimensional array is the simplest form of a multidimensional array.
dataType arrayName[x][y];
int x[10][20];
• This type of initialization make use of nested braces. Each set of inner braces represents one row. In the
above example there are total three rows so there are three sets of inner braces.
• In 2-D array, it is optional to specify the first dimension while initialization but the second dimension
should always be present.
int a[][3] = {{1, 10}, {2, 20, 200}, {3}, {4, 40, 400}};
Here, first dimension is taken 4 since there are 4 rows in initialization list.
19
• Compilation Error:
int a[4][] = {{1, 10}, {2, 20, 200}, {3}, {4, 40, 400}};
int a[][] = {{1, 10}, {2, 20, 200}, {3}, {4, 40, 400}};
1 2 3
4 5 6
7 8 9
20
1.11.4.1 Row Major ordering
In row major ordering, all the rows of the 2D array are stored into the memory contiguously. The 1st row of
the array is stored into the memory completely, then the 2nd row of the array is stored into the memory completely
and so on till the last row.
1 2 3 4 5 6 7 8 9
Address of an element a[i][j] of the array stored in row major order is calculated as:
Example: a[10...30, 55...75], base address of the array (BA) = 0, size of an element = 4 bytes. Find the
location of a[15][68].
Address of a[15][68] = 0 + (21(15 − 10) + (68 − 55)) ∗ 4
= ((21 ∗ 5) + 13) ∗ 4
= 472
Example: a[4...7, -1...3], base address of the array (BA) = 100, size of an element = 2 bytes. Find the
location of a[6][2].
Address of a[6][2] = 100 + (5(6 − 4) + (2 − (−1))) ∗ 2
= 100 + (5 ∗ 2 + 3) ∗ 2
= 126
21
1.11.4.2 Column Major ordering
According to the column major ordering, all the columns of the 2D array are stored into the memory contiguously.
The 1st column of the array is stored into the memory completely, then the 2nd column of the array is stored into
the memory completely and so on till the last column of the array.
1 4 7 2 5 8 3 6 9
Address of an element a[i][j] of the array stored in column major order is calculated as:
A[-5 ... 20][20 ... 70], BA = 1020, Size of element = 8 bytes. Find the location of a[0][30] in column
major implementation.
Address of a[0][30] = 1020 + ((0 − (5)) + 26(30 − 20)) ∗ 8
= 1020 + (5 + (26 ∗ 10)) ∗ 8
= 3140
A[-20 ... 20][10 ... 35], BA = 500, Size of element = 1 bytes. Find the location of a[0][30] in column
major implementation.
Address of a[0][30] = 500 + ((0 − (−20)) + 41(30 − 10)) ∗ 1
= 500 + (20 + 41 ∗ 20) ∗ 1
= 1340
22
1.11.5 Home Assignment of 2-D array
• Write a C program to addition of two matrix.
• Write a C program to multiplication of two matrix.
• Write a C program to transpose of a matrix.
23
1.12 Sparse Matrix and its representation using Array
• What is a matrix?
– A matrix can be defined as a two-dimensional array having ’m’ rows and ’n’ columns.
– A matrix with m rows and n columns is called m × n matrix.
– It is a set of numbers that are arranged in the horizontal or vertical lines of entries.
24
1.12.2 Array representation of the sparse matrix
• Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
• Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of
no use in most of the cases.
• So, instead of storing zeroes with non-zero elements, we only store non-zero elements.
• To avoid such wastage, we can store only non-zero elements. If we store only non-zero elements, it reduces
the traversal time and the storage space.
• This means storing non-zero elements with triples- (Row, Column, value).
• 2D array is used to represent a sparse matrix in which there are three rows named as
– Row: Index of row, where non-zero element is located
– Column: Index of column, where non-zero element is located
– Value: Value of the non zero element located at index – (row,column)
• Example: Let’s understand the array representation of sparse matrix with the help of the example given
below. Consider the sparse matrix:
• In the above figure, we can observe a 5x4 sparse matrix containing 7 non-zero elements and 13 zero elements.
• The above matrix occupies 5x4 = 20 memory space.
25
• The tabular representation of the above matrix is given below:
• In the above structure, first column represents the rows, the second column represents the columns, and the
third column represents the non-zero value.
• The first row of the table represents the triplets. The first triplet represents that the value 4 is stored at 0th
row and 1st column. Similarly, the second triplet represents that the value 5 is stored at the 0th row and 3rd
column. In a similar manner, all triplets represent the stored location of the non-zero elements in the matrix.
• The size of the table depends upon the total number of non-zero elements in the given sparse matrix.
• Above table occupies 7 ∗ 3 = 21 memory space which is more than the space occupied by the sparse matrix.
So, what’s the benefit of using the sparse matrix?
• Consider the case if the matrix is 8 ∗ 8 and there are only 8 non-zero elements in the matrix, then the space
occupied by the sparse matrix would be 8 ∗ 8 = 64, whereas the space occupied by the table represented
using triplets would be 8 ∗ 3 = 24.
• Example:
• Time Complexity: O(NM), where N is the number of rows in the sparse matrix, and M is the number of
columns in the sparse matrix.
• Auxiliary Space: O(NM), where N is the number of rows in the sparse matrix, and M is the number of
columns in the sparse matrix.
26
// C program for Sparse Matrix Representation using Array
#include<stdio.h>
int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
int compactMatrix[3][size];
printf("\n");
}
return 0;
}
27
1.13 Sample Question
1. Describe the traversal algorithm for a linear array.
28