UNIT-2 Array
UNIT-2 Array
Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 9.
Declaration of Array
In C, the array must be declared properly before using it with its name and length. There are
three syntaxes in which we can declare arrays in a c program
1
Syntax 1
int A[7] = {21,56,32,52,63,12,48} – Declaring the length and elements of array
#include<stdio.h>
int main{
int a[7] = {21,56,32,52,63,12,48};
int i;
for(i=0;i<7;i++){
printf(“%d\n”,a[i]);
}
return 0;
}
Syntax 2
int A[]={21,56,32,52,63,12,48} – Declaring the length of elements of array
C Program
#include<stdio.h>
int main{
int a[] = {21,56,32,52,63,12,48};
int i;
for(i=0;i<7;i++){
printf(“%d\n”,a[i]);
}
return 0;
}
// declaration, assignment, and accessing arrays
#include <stdio.h>
int main () {
2
}
Basic Operations
Following are the basic operations supported by an array.
Traverse − 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.
Update − Updates an element at the given index.
Traverse Operation
This operation is to traverse through the elements of an array.
Example
Following program traverses and prints the elements of an array:
#include <stdio.h>
main() {
int A[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("A[%d] = %d \n", i, A[i]);
}
}
When we compile and execute the above program, it produces the following result −
Output
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
3
Insertion Operation
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.
Here, we see a practical implementation of insertion operation, where we add data at the end of
the array −
Example
Following is the implementation of the above algorithm −
#include <stdio.h>
main() {
int A[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k) {
A[j+1] = A[j];
j = j - 1;
}
A[k] = item;
4
A[4] = 8
The array elements after insertion :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 10
A[4] = 7
A[5] = 8
For other variations of array insertion operation click here
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all elements of
an array.
Algorithm
Consider A is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to delete an element available at the Kth position of A.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set A[J] = A[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Example
Following is the implementation of the above algorithm −
#include <stdio.h>
void main() {
int A[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("A[%d] = %d \n", i, A[i]);
}
j = k;
while( j < n) {
A[j-1] = A[j];
j = j + 1;
}
n = n -1;
5
printf("The array elements after deletion :\n");
Search Operation
You can perform a search for an array element based on its value or its index.
Algorithm
Consider A is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to find an element with a value of ITEM using sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF A[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Example
Following is the implementation of the above algorithm −
#include <stdio.h>
void main() {
int A[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
6
printf("A[%d] = %d \n", i, A[i]);
}
while( j < n){
if( A[j] == item ) {
break;
}
j = j + 1;
}
printf("Found element %d at position %d\n", item, j+1);
}
When we compile and execute the above program, it produces the following result −
Output
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
Found element 5 at position 3
Update Operation
Update operation refers to updating an existing element from the array at a given index.
Algorithm
Consider A is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to update an element available at the Kth position of A.
1. Start
2. Set A[K-1] = ITEM
3. Stop
Example
Following is the implementation of the above algorithm −
#include <stdio.h>
void main() {
int A[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("A[%d] = %d \n", i, A[i]);
}
A[k-1] = item;
printf("The array elements after updation :\n");
7
for(i = 0; i<n; i++) {
printf("A[%d] = %d \n", i, A[i]);
}
}
When we compile and execute the above program, it produces the following result −
Output
The original array elements are :
A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 7
A[4] = 8
The array elements after updation :
A[0] = 1
A[1] = 3
A[2] = 10
A[3] = 7
A[4] = 8
Multi-dimensional arrays
Multi-dimensional arrays are an extended form of one-dimensional arrays and are frequently
used to store data for mathematic computations, image processing, and record management.
A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in
tabular form. Data in multidimensional arrays are stored in row-major order.
The general form of declaring N-dimensional arrays is:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array
size1, size2,… ,sizeN: Sizes of the dimension
Examples:
Two dimensional array: int two_d[10][20];
Three dimensional array: int three_d[10][20][30];
Size of Multidimensional Arrays:
The total number of elements that can be stored in a multidimensional array can be calculated
by multiplying the size of all the dimensions.
For example:
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.
Two-Dimensional Array
8
Two – dimensional array is the simplest form of a multidimensional array. We can see a two –
dimensional array as an array of one-dimensional array for easier understanding.
The basic form of declaring a two-dimensional array of size x, y:
Syntax:
data_type array_name[x][y];
Here, data_type is the type of data to be stored.
We can declare a two-dimensional integer array say ‘x’ of size 10 by 20 as:
int x[10][20];
Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row
number and ‘j’ is the column number.
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row
number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1). A two –
dimensional array ‘x’ with 3 rows and 3 columns is shown below:
Initializing Two – Dimensional Arrays: There are various ways in which a Two-
Dimensional array can be initialized.
First Method:
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
The above array has 3 rows and 4 columns. The elements in the braces from left to right are
stored in the table also from left to right. The elements will be filled in the array in order, the
first 4 elements from the left in the first row, the next 4 elements in the second row, and so on.
Second Method:
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
Third Method:
int x[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
scanf(“%d”, &x[i][j]);
}
}
9
Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are
accessed using the row indexes and column indexes.
Example:
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You can verify it in
the above figure. Let us check the following program where we have used a nested loop to
handle a two-dimensional array −
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
10
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
11
for (j = 0; j < n; j++) {
printf("%d\t", c[i][j]);
}
printf("\n");
}
return 0;
}
if (n != p) {
printf("Matrix is incompatible for multiplication\n");
} else {
printf("Enter the elements of Matrix-A:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", & a[i][j]);
}
}
12
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
printf("%d\t", res[i][j]);
}
printf("\n");
}
}
return 0;
}
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
13
Sparse matrix
A sparse matrix is a matrix in which many or most of the elements have a value of zero. This is
in contrast to a dense matrix, where many or most of the elements have a non-zero value. Sparse
matrices are used in specific ways in computer science, and have different data analysis and
storage protocols and techniques related to their use.
A matrix is a two-dimensional data object made of m rows and n columns, therefore having
total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse
matrix.
Why to use Sparse Matrix instead of simple matrix ?
Storage: There are lesser non-zero elements than zeros and thus lesser memory can be
used to store only those elements.
Computing time: Computing time can be saved by logically designing a data structure
traversing only non-zero elements..
Example:
00304
00570
00000
02600
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. This means storing non-zero elements with triples- (Row,
Column, value).
The byte data type is an 8-bit (1 byte) signed two’s complement integer. It has a minimum value of -128
and a maximum value of 127 (inclusive).
short: The short data type is a 16-bit (2 byte) signed two’s complement integer.
int: The int data type is a 4-bytes(32 bits) signed two’s complement integer.
14
int length;
long: The long data type is a 8 bytes (64-bits) signed two’s complement integer.
2-D array
15
To find the address of any element in a 2-Dimensional array there are the following two ways-
Row Major Order
Column Major Order
1. Row Major Order:
Row major ordering assigns successive elements, moving across the rows and then down the
next row, to successive memory locations. In simple language, the elements of an array are
stored in a Row-Wise fashion.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.
Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each
element is 1 Byte in memory. Find the address of arr[8][6] with the help of row-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
16
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
2. Column Major Order:
If elements of an array are stored in a column-major fashion means moving across the column
and then to the next column then it’s in column-major order. To find the address of the element
using column-major order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.
Example: Given an array arr[1………10][1………15] with a base value of 100 and the size of
each element is 1 Byte in memory find the address of arr[8][6] with the help of column-major
order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
From the above examples, it can be observed that for the same position two different address
locations are obtained that’s because in row-major order movement is done across the rows and
17
then down to the next row, and in column-major order, first move down to the first column and
then next column. So both the answers are right.
So it’s all based on the position of the element whose address is to be found for some cases the
same answers is also obtained with row-major order and column-major order and for some cases,
different answers are obtained.
Calculate the address of any element in the 3-D Array:
A 3-Dimensional array is a collection of 2-Dimensional arrays. It is specified by using three
subscripts:
Block size
Row size
Column size
More dimensions in an array mean more data can be stored in that array.
Example:
3-D array
To find the address of any element in 3-Dimensional arrays there are the following two ways-
Row Major Order
Column Major Order
1. Row Major Order:
To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = B + W (M * N(i-x) + N *(j-y) + (k-z))
Here:
18
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width
Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each
element is 2 Bytes in memory find the address of element arr[5][-1][8] with the help of row-
major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 5
Column Subset of an element whose address to be found J = -1
Block Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of row/start row index of matrix x = 1
Lower Limit of column/start column index of matrix y = -4
Lower Limit of blocks in matrix z = 5
M = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N = Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6
Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
Solution:
Address of[][][] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * ((4 * 6 + 3) * 6 + 3)
= 400 + 2 * (165)
= 730
2. Column Major Order:
To find the address of the element using column-major order, use the following formula:1
Address of A[i][j][k = B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
19
y = Lower Bound of Column
z = Lower Bound of Width
Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each
element is 4 Bytes in memory find the address of element arr[3][3][3] with the help of column-
major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of row/start row index of matrix x = 1
Lower Limit of column/start column index of matrix y = -5
Lower Limit of blocks in matrix z = -10
M = Upper Bound – Lower Bound + 1 = 5 + 5 + 1 = 11
N = Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (k – z) + (j – y))
Solution:
Address of[3][3][3] = 400 + 4 * {[(3 – 1)] * 16 + [3 + 10] ]} * 11 + [3 + 5]
= 400 + 4 * ((32 + 13) * 11 + 8)
= 400 + 4 * (503)
= 400 + 2012
= 2412
Applications of Array Data Structure:
Below are some applications of arrays.
Arrays are used to implement data structures like a stack, queue, etc.
Arrays are used for matrices and other mathematical implementations.
Arrays are used in lookup tables in computers.
Arrays can be used for CPU scheduling.
20
Applications of Array in C:
Arrays are used to implement vectors, and lists in C++ STL.
Arrays are used as the base of all sorting algorithms.
Arrays are used to implement other DS like a stack, queue, etc.
Used for implementing matrices.
Data structures like trees also sometimes use the array implementation since arrays are
easier to handle than pointers. For example, a segment tree uses array implementation.
Binary search trees and balanced binary trees are used in data structures such as a heap,
map, and set, which can be built using arrays.
Graphs are also implemented as arrays in the form of an adjacency matrix.
21