Unit-2 Arrays
Unit-2 Arrays
Chapter-2 Arrays
Introduction
In computer programming, an array is one of the simplest data structures. An array is a
collection of similar data elements which are stored contiguously in memory locations, usually
of the same size and data type. Individual elements are accessed by their position in the array.
The position is given by an index, which is also called a subscript. The index usually uses a
consecutive range of integers, such as 1,2,3… etc. In this chapter, we work with one-
dimensional arrays and two-dimensional arrays.
Concept of Arrays
A general variable is used to store one value only at a time. But what will you do if somebody
tells you to store 100 integer values or 100 real values or 100 characters? The obvious
solution to such problem is arrays. Arrays are useful when the numbers of elements are fixed.
An array is a finite set of similar elements stored in adjacent memory locations. Arrays provide
a way to store a large number of variables of same type under the same name. Each variable,
called an element, in an array must have the same data type, and they are distinguished from
each other by an array index.
Array – a set of similar data items which are stored in contiguous memory locations
34 28] 65 30 18 57 43 29 85 10
An array containing ‘n’ number of elements is referenced using an index that varies from 0 to
n-1. For example, the elements of an array num[n] containing ‘n’ elements are denoted by
num[0], num[1], num[2], …., num[n-1], where 0 is the lower bound and ‘n-1’ is the upper
bound. An array is further categorized as:
1. One-dimensional array
2. Multi-dimensional array
A multi-dimensional array can be a 2-D array, 3-D array, 4-D array, etc. Following examples
show this:
num[4][5] a 2-D array with 4 rows and 5 columns holding 20 (4x5) elements
num[3][4][5] a 3-D array with three 2-D arrays each of which is having 4 rows and 5
columns, thus holding total 60 (3x4x5) elements
For example, if we want to store 100 integer values then its array declaration will be as:
int a [100] ;
Here ‘a’ is an array of 100 integer elements. The individual element of an array ‘a’ is accessed
with the help of a subscript (index). Here the elements of ‘a’ array are denoted by a[0], a[1],
a[2], a[3], …., a[99]. The number ‘k’ in a[k] is called a subscript and a[k] is called a subscripted
variable. In ‘C’ language, the subscript starts from 0.
If we want to access say 40th location in array a [ ], then we will use following notation
item = a [39] ;
a [59] = 28;
We place data items into an array of ‘size’ using for loop as:
The first data item in array a [ ] is placed into location &a [0], that’s why i has 0 initial value and
this process will be repeated until i reaches (size – 1).
In the same fashion if we want to display the data items of array a[ ], we will use the following
for – loop:
Single dimensional arrays are initialized when they are declared. For example,
int a[10] = {12, 26, 83, 54, 15, 96, 47, 18, 39, 20};
Here 12 is assigned to a[0], 26 is assigned to a[1], 83 is assigned to a[2] and so on. Here one
should remember that when a single dimensional array is initialized then it is optional to
mention the size of the array, as follows:
int a[ ] = {12, 26, 83, 54, 15, 96, 47, 18, 39, 20};
Declaring array
size is optional
As studied earlier, elements of a single dimensional array are stored contiguously in memory.
For example,
int a[10] = {12, 26, 83, 54, 15, 96, 47, 18, 39, 20};
Value
12 26 83 54 15 96 47 18 39 20
6400 6402 6404 6406 6408 6410 6412 6414 6416 6418
Address
The starting address of the very first data item in an array is called as base address of the
array. If we have ‘n’ number of data items in an array along with its base address, then we can
3
Chapter-2 Arrays
easily find out the address of any data item. In single-dimensional array, the address of any
data item, say A[I], can be calculated as:
Here BaseAddress is the address of very first element, ‘w’ is the size of data item in bytes (2
for integer, 4 for float, 1 for character) and LB is the lower bound of the array (in ‘C’ language
the value of LB is always 0). Let us understand this by taking some simple examples:
Example-1 : Let we have an array A of 20 integer numbers with its base address 16080
and we want to find out the address of 16th data item.
Solution : The formula Address of finding the address of Ith data is as:
Example-2 : Consider the one dimensional float array LA. Base address is 2000, w = 4,
LB = 1 and UB = 8. Calculate the address of LA[4] and LA[6].
Solution : The formula Address of finding the address of Ith data is as:
1. Traversing
2. Inserting
3. Deleting
4. Searching
1. Sorting
2. Merging
are discussed in chapter-6. Now let us look at main operations that are performed on single
dimensional array.
Algorithm : Traverse
1. Set I = Start
2. Repeat through Step-4 while (I< Final)
3. Process element A[I]
4. Increment the value of I as I = I+1
5. Exit
4
Chapter-2 Arrays
Implementation : Traverse
#include <stdio.h>
#define size 100
main()
{
int i, n, a[size];
printf("\nEnter number of elements of an array - ");
scanf("%d", &n);
for(i=0; i<n;i++)
{
printf("Element - %d : ", i+1);
scanf("%d", &a[i]);
}
printf("\nArray elements are as:\n");
traversing(a,0,n);
}
traversing(int a[], int start, int final)
{
int i;
for(i=start; i<final;i++)
printf("%d\t", a[i]);
}
In this an element is searched from a set of numbers. It is started from initial (starting) value to
the final value. If item is found at any location then there is no need to go further in the array. If
item is not found at any location then it displays the message – “Item not found”. This
searching technique is called as linear searching technique. Here is the searching algorithm:
Algorithm : Search
1. Initialize Flag = 0
2. Initialize I = 0
3. Repeat through Step-6 while (I< N)
4. If Item = A[I] then go to Step 5; otherwise go to Step 6
5. Set Flag = 1 and go to Step-7
6. Increment the value of I as I = I+1
7. If Flag = 1 then display the message – “Item found”;
Otherwise display the message – “Item not found”
8. Exit
5
Chapter-2 Arrays
Implementation : Search
Program-2.2 : Write a program which finds whether a given item is in the array or not.
#include <stdio.h>
#define size 100
main()
{
int i, n, a[size], item;
printf("\nEnter number of elements of an array - ");
scanf("%d", &n);
for(i=0; i<n;i++)
{
printf("Elements - %d : ", i+1);
scanf("%d", &a[i]);
}
printf("\nEnter the element to be searched - ");
scanf("%d", &item);
Search(a, n,item);
}
Search (int a [ ], int n, int item)
{
int flag = 0, i ;
for (i = 0 ; i <= n-1; i++ )
{
if (item == a[i] )
{
flag = 1;
break;
}
}
if (flag == 1 )
printf (“Item %d found”, item) ;
else
printf (“Item %d not found”, item) ;
}
By inserting we mean addition of a new element into an array at any specific location. Let we
have an array of 10 elements as shown in figure 2.2 and we want to insert a new element 22
at 6th location then we have to move each elements of the array from position 6 to 9 to one
position down.
0 15 15
1 21 21
2 17 17
3 25 25
4 -40 -40
5 54 54
6 29 22 New element
7 17 29
8 20 17
9 45 20
45
Figure 2.2
In other words a[9] is shifted to a[10], a[8] is shifted to a[9], a[7] is shifted to a[8] and in last
a[6] is shifted to a[7]. After this we will insert the new element as
a [6] = 22;
After insertion the size of array is also increased by one. Here is the insertion algorithm.
Algorithm : Insertion
Perform the following steps if the array is not full i.e. M <> N:
1. Initialize J = M
2. If Pos >= J then insert the element at the end of the array as –
A[J] = Item; and go to Step-8
Otherwise go to Step-4
3. Insert the item at proper position
4. Repeat through Step-6 while (J >= Pos )
5. Update A[J] as A[J] = A[J-1] ;
6. Decrement the value of temp as J = J - 1;
7. Insert the Item at ‘Pos-1’ as:
A[Pos-1] = item;
8. Increment the value of M as M = M+1
9. Exit
Implementation : Insertion
if (*m == n)
{
printf("\nArray full. Item can not be inserted.");
getch();
return;
}
else
{
j = *m;
if (pos >= j)
{
a[j] = item;
printf("\nItem is inserted at the end.") ;
}
else
{
while (j >= pos )
{
a [j] = a[j-1] ;
j--;
}
a[pos-1] = item;
printf ("\nItem is inserted successfully.");
}
(*m)++;
}
}
else
{
printf("\nYou have entered wrong position. ");
printf("\nPlease enter correct dimension.");
}
}
Program-2.3 : Write a program which inserts a new element in the array, provided that
array is not full.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
{
int j,temp;
Deletion of an element is very simple, if it is deleted at end. But if an element is deleted in the
mid or any specific location, say ith location, then we have to shift some elements upwards. Let
we have an array of 10 elements as shown in figure 2.3. Now if we want to delete an element
of 6th location then we have to move each elements of the array from position 6 to 9 to one
position upward. In other words a[9] is shifted to a[8], a[8] is shifted to a[7], and in last a[7] is
shifted to a [6]. After deletion, the size of array is decreased by one.
9
Chapter-2 Arrays
0 15 15
1 21 21
2 17 17
3 25 25
4 -40 -40
5 54 54
6 29 Deleted Item 17
7 17 20
8 20 45
9 45
Figure 2.3
Algorithm : Deletion
1. Initialize Flag = 0
2. If Pos >= M then go to Step-3;
Otherwise go to Step-10
3. Update Flag = 1
4. Set J = Pos-1
5. Access the Item stored at J as Item = A[J]
6. Repeat through Step-8 while (J < M )
7. Set A[J] = A[J+1] ;
8. Increment the value of ‘J’ - J = J+1;
9. Decrement the value of M – M = M – 1
10. If Flag = 1 then display the message – “Item deleted successfully”
Otherwise display the message – “Item not deleted successfully”
11. Exit
}
10
Chapter-2 Arrays
Program-2.4 : Write a program which deletes an element of given position in the array,
provided that you have entered correct position.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
const int n = 20;
main()
{
int a[n];
int i,m, pos;
printf("\nEnter number of elements < 20 - ");
scanf("%d", &m);
if (m>20)
{
printf("\nPlease enter number of elements less than 20.");
getch();
exit(0);
}
printf("\Please enter %d elements.\n",m);
for(i=0; i<m;i++)
scanf("%d", &a[i]);
printf("\nPlease enter position of the item you want to delete - ");
scanf("%d", &pos);
Deletion(a, &m, pos); /* Calling Deletion function */
printf("\nArray after deletion is as:\n");
for(i=0;i<m;i++)
printf("\n%d", a[i]);
}
Deletion (int a[ ], int *m, int pos)
{
int j, item, flag =0;
if (pos < *m)
{
flag = 1;
j = pos-1;
item= a [j];
while (j < *m)
{
a [j] = a[j+1] ;
j++;
}
(*m)- -;
}
if (flag == 1)
printf ("\nDeleted item = %d", item);
else
printf ("\nItem can not be deleted");
here rows and columns represent total number of rows and columns respectively in a two-
dimensional array named arrayname and datatype is the type of the element that arrayname
contains.
Two dimensional Arrays – a set of similar data items which are stored in contiguous
memory locations and each element is accessed by two subscripts – one for the row and
another for the column
For example, if you want to declare an array of int that has 4 numbers of rows and 6 numbers
of columns then it is declared as:
int a[4][6];
a[2][4]
would refer to the integer value in the third row and the fifth column.
Similarly we can read back data from a two-dimensional array by using a nested for loop as:
Like single dimensional arrays, we can also initialize a two-dimensional array as:
int a[4][4] = {
{4, 5, 7, 9},
{2, 6, 2, 1},
{6, 1, 3, 5},
{2, 8, 9, 3}
};
If any of the inner initializers list have fewer initializers than defined in array dimensions then
the remaining elements are initialized to zero.
12
Chapter-2 Arrays
In this the elements of two-dimensional array are stored row by row, that is first row of two-
dimensional array is stored first, then second, third, fourth. And so on. Row major order is
used most notably by statically-declared arrays in C.
4 9 7 8
2 5 11 14
15 6 1 3 3x4
4 9 7 8 2 5 11 14 15 6 1 3
In general for an array A[M, N], the address of element A[I, J] is:
Here
Base address = base address of a two dimensional array
w = size of element in bytes ( 1 – char, 2 – int, 4 – float)
N = total number of columns
Let us take an example of address calculation. If we have an array A [4][5] Of real numbers
having its base address 64080 and we want to find out the address of A [2][1].
In this example
Base address = 64080
Size = 4
N=5
I=2
J=1
In this the elements of two-dimensional array are stored column by column, that is first column
of two-dimensional array is stored first, then second, third, fourth. And so on. Row major order
is used most notably in FORTRAN.
4 9 7 8
2 5 11 14
15 6 1 3
13
Chapter-2 Arrays
4 2 15 9 5 6 7 11 1 8 14 3
The basic formula for calculating the address of element A[I, J] in an array of (M x N) elements
in column order as :
Where
Base address = base address of a two dimensional array
w = size of element in bytes ( 1 – char, 2 – for int, 4 – float)
M = total number of columns
Let us take an example of address calculation. If we have an array A [4][5] Of real numbers
having its base address 64080 and we want to find out the address of A [2][1].
In this example
Base address = 64080
Size = 4
M=4
I=2
J=1
ReadMatrix(a, 3, 3);
The declaration of number of columns with array name ‘a’ is compulsory in function definition
of ReadMatrix ‘a’ as:
compulsory
But it is a good programming habit to declare number of rows as well as number of columns in
function definition.
Addition of Matrices
Let we have two matrices A and B of size (m * n). The sum of A and B, written as A+B, is
obtained by adding the corresponding elements of A and B. The ij th element of A+B is given by
4 5 7 2 5 6
A = 9 1 2 B= 8 7 2
10 5 2 1 3 4
6 10 13
A + B = 17 8 4
11 8 6
Algorithm : AddMatrix
Implementation : AddMatrix
AddMmatrix (int a[10][10], int row1, int col1, int b[10][10], int row2, int col2, int c[10][10])
{
int i, j;
if ((row1== row2)&&(col1==col2))
{
for (i=0; i<row1; i++)
{
for (j=0; j<col1; j++)
c [i][j] = a[i][j] + b[i][j];
}
}
else
{
printf (“\nAddition not possible. Rows and Columns of both matrices do not
match”);
getch ();
exit (0);
15
Chapter-2 Arrays
}
}
Program-2.8 : Write a program which adds two given matrices, provided that both have
same dimensions.
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, r1, c1, r2, c2;
printf(“\nEnter the dimension of first matrix :”);
scan(“%d %d”, &r1, &c1);
printf(“\nEnter the elements of first matrix :\n”);
for (i=0; i<r1; i++)
{
for (j=0; j<c1; j++)
scanf(“%d”, &a[i][j]);
}
AddMmatrix (int a[10][10], int row1, int col1, int b[10][10], int row2, int col2, int c[10][10])
{
int i, j;
if ((row1== row2)&&(col1==col2))
{
for (i=0; i<row1; i++)
{
for (j=0; j<col1; j++)
c [i][j] = a[i][j] + b[i][j];
}
}
else
{
printf (“\nAddition not possible. Rows and Columns of both matrices do not
match”);
getch ();
exit (0);
}
}
As you have added two matrices, you can subtract two matrices.
Multiplication of Matrices
Let we have two matrices A and B of size (m * n) and (n*p). The multiplication of A and B,
written as A * B, is obtained by multiplying the corresponding elements of A and B.
The ijth element of A-B is given by
16
Chapter-2 Arrays
Cij = [A x B]ij = Ai1 x B1j + Ai2 x B2j + Ai3 x B3j + ----- + Ain x Bnj
n
Cij = Aik x Bkj
k=1
4 5 7 2 5 6
A = B=
9 1 2 8 7 2
10 5 2 1 3 4
55 76 62
A x B = 28 58 64
62 91 78
Algorithm : MultMatrix
Implementation : MultMatrix
MultMatrix(int a[10][10], int row1, int col1, int b[10][10], int row2, int col2, int c[10][10])
{
int i, j, k;
if (col1== row2)
{
for (i=0; i<row1; i++)
{
for (j=0; j<col2; j++)
{
17
Chapter-2 Arrays
c [i][j] = 0;
for (k=0; k<col1; k++)
c [i][j] = c[i][j]+a[i][k] * b[k][j];
}
}
}
else
{
printf (“\nMultiplication not possible. Number of columns of first matrix is not
equal to number of rows of second matrix”);
getch ();
exit (0);
}
}
Program-2.9: Write a program which adds two given matrices, provided that the number
of columns of first matrix is equal to the number of rows of second matrix.
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, r1, c1, r2, c2;
printf(“\nEnter the dimension of first matrix :”);
scan(“%d %d”, &r1, &c1);
printf(“\nEnter the elements of first matrix :\n”);
for (i=0; i<r1; i++)
{
for (j=0; j<c1; j++)
scanf(“%d”, &a[i][j]);
}
MultMatrix(int a[10][10], int row1, int col1, int b[10][10], int row2, int col2, int c[10][10])
{
int i, j, k;
if (col1== row2)
{
for (i=0; i<row1; i++)
{
for (j=0; j<col2; j++)
{
c [i][j] = 0;
for (k=0; k<col1; k++)
c [i][j] = c[i][j]+a[i][k] * b[k][j];
}
}
}
else
{
18
Chapter-2 Arrays
Transpose of a Matrix
4 5 7
A = 9 1 2
10 5 2
4 9 10
AT = 5 1 5
7 2 2
Algorithm : Transpose
1. Initialize I = 0
2. Repeat through Step-7 while (I < Row1)
3. Initialize J = 0
4. Repeat through Step-6 while (J < Col1)
5. Assign B[I][J] = A[J]I]
6. Increment the value of J as J = J + 1
7. Increment the value of I as I = I +1
8. Exit
Implementation : Transpose
elements in that array. If our program needs to store 75 elements into this array then it will
overflow and may overwrite some important data in your memory. Similarly if we need only 5
elements then a lot of memory space will go in waste. This drawback is overcome by dynamic
memory allocation in which the memory space for the data items are created at run time.
C provides two library functions malloc () and calloc () to created memory during run time.
The syntax of using malloc () and calloc () function is as:
The malloc() function allocates space in bytes. It returns a pointer to the newly allocated
memory block. Hoever if there is not enough space then it return a NULL value. Similarly the
calloc () function allocates spaces for ‘n’ number of items, and ‘size’ is the size of the data
item. It returns a pointer to the newly allocated memory block or NULL if there is not enough
space exists in memory.
For example, let we want to create memory space for 20 integers during runtime then malloc ()
and calloc () functions are called as:
The free() function is used to release the dynamically allocated memory. When you use these
dynamic memory allocation and deallocation functions don’t forget to include “alloc.h” header
files because these functions are defined in this header file.
Pointer plays an important role in dynamic memory allocation. We know that the malloc () and
calloc () functions returns the address of first memory space otherwise it returns a NULL and
this address must be stored in a pointer variable. If we allocate memory for integers then it
must be stored in integer pointer only, for float values we use float pointer and for character
values we use char pointer only.
printf (“\n How many real number you want to create dynamically? ”);
scanf (“%f”, &num2);
20
Chapter-2 Arrays
Difference between malloc() and calloc() – Similarly we can use calloc() function to create
memory space dynamically. The only difference between malloc() and calloc() is that the
default value of data items in malloc() is garbage whereas in case calloc() the default value is
0.
For a user-defined data type, C provides sizeof() operator to calculate the total size of data
type in bytes.
You can release the dynamically allocated memory used free() function as:
free (iptr);
free (fptr);
Like this you can also create memory dynamically for two-dimensional array. Following code
segment illustrates this:
int row1, col1; /* row1 and col1 are number of rows and columns of first matrix */
int row2, col2; /*row2 and col2 are number of rows and columns of first matrix */
….
int *mptr1 = malloc(row1*col1* sizeof(int)); /* creates memory dynamically for first matrix */
int *mptr2 = malloc(row2 * col2 * sizeof(int)); /* creates memory dynamically for second matrix */
….
free(mptr1);
free(mptr2);
21
Chapter-2 Arrays
Now let us see a simple program that multiples two matrices using pointer notations.
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
main()
{
int row1, row2, col1, col2;
int i, j, k;
printf("\nEnter number of rows of matrix-1 = ");
scanf(“%d”, &row1);
printf("Enter number of columns of matrix - 1 = ");
scanf(“%d”,&col1);
printf("\nEnter number of rows of matrix-2 = ");
scanf(“%d”, &row2);
printf("Enter number of columns of matrix - 2 = ");
scanf(“%d”,&col2);
if (col1!=row2)
{
printf("\nColumn of Matrix-1 should be equal to row of Matrix-2.");
exit(0);
}
10 10 10
20 20 20
30 30 30
Similarly using pointer notations you can subtract and multiply two matrices.