You are on page 1of 22

1

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

Figure 2.1 show the representation of an array.

34 28] 65 30 18 57 43 29 85 10

Figure 2.1 An array of 10 integers

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[5] a 1-D array of holding 10 elements

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

Single Dimensional Array


A single-dimensional array is a collection of similar data items whose individual item can be
accessed by using an index that indicates the position of the item within the collection. The
syntax of defining a single-dimensional array is as:

datatype arrayname [size ];

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.

Subscript – a notation (variable) used in array to access an individual element


2
Chapter-2 Arrays

The above things are represented as:

a[0] a[1] a[2] a[3] … … … a[97] a[98] a[99]

If we want to access say 40th location in array a [ ], then we will use following notation

item = a [39] ;

And if we want to store an integer 28 at 60 th location then we will assign it as:

a [59] = 28;

Reading data items into Array

We place data items into an array of ‘size’ using for loop as:

for (i = 0; i < size ; i++ )


scanf (“%d”, &a[i]);

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).

Displaying data items of an Array

In the same fashion if we want to display the data items of array a[ ], we will use the following
for – loop:

for (i = 0; i < size ; i++ )


printf (“%d”, a[i]);

Initializing a Single-dimensional Arrays

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

Memory representation of Single Dimensional Array

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};

This array is represented in memory as:

Value

12 26 83 54 15 96 47 18 39 20
6400 6402 6404 6406 6408 6410 6412 6414 6416 6418

Address

Figure 2.2 – Memory Representation of Single Dimensional Array

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:

Address of A[I] = BaseAddress + w * (I – LB)

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:

A[I] = BaseAddress + w * (I – LB)

Here BaseAddress = 16080, w = 2, I = 16 and L = 0. The address of A[16] of calculated as:

Address of A [16] = 16080 + 2 (16 – 0)


= 16080 + 32
= 16112

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:

LA[I] = BaseAddress + w * (I – LB)

Thus address of LA[4] = 2000 + 4 * (4 – 1 ) = 2000 + 4 * 3 = 2000 + 12


= 2012

Address of LA[6] = 2000 + 4 * (6 – 1 ) = 2000 + 4 * 5 = 2000 + 20


= 2020

Operation on Single Dimensional Arrays


There are several operations that are performed on single dimensional arrays. Some main
operations are:

1. Traversing
2. Inserting
3. Deleting
4. Searching

where as other major operations, such as:

1. Sorting
2. Merging

are discussed in chapter-6. Now let us look at main operations that are performed on single
dimensional array.

Traversing One Dimensional Array


Traversing refers to processing of each and every element of array exactly once and to apply
some processing on that element. Here is the traversing algorithm.

Algorithm : Traverse

Traverse (A, Start, Final)

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

The traversing algorithm is implemented as:

Implementation : Traverse

Traverse (int a[], int start, int final)


{
int i;
for (i = start; i < final; i++)
printf (“\n %d”, a[i]) ; /* displaying array elements on screen */
}

Let us put this idea into a program.

Program-2.1 : Write a program which illustrates the concept of traversing of an array.

#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]);
}

The output of this program is as….

Enter number of elements of an array – 5


Element – 1 : 12
Element – 2 : 34
Element – 3 : 27
Element – 4 : 54
Element – 5 : 70

Array elements are as:


12 34 27 54 70

2.4.2 Searching into One Dimensional Array

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

Search (A, N, Item)


Here A is an array of N number of elements and Item be the data item
to be searched

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

The searching algorithm is implemented is as:

Implementation : Search

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) ;
}

Let us put this idea into a program.

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) ;
}

The output of this program is as….

Enter number of elements of an array – 5


Element – 1 : 12
Element – 2 : 34
Element – 3 : 27
Element – 4 : 54
Element – 5 : 70
Enter the element to be searched – 54
Item 54 found
6
Chapter-2 Arrays

2.4.3 Inserting an Element into One Dimensional Array

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

Insertion (A, M, N, Pos, Item)


Here A is an array of size N, M is number of elements present in an
array. Item is the data item to be inserted at position Pos.

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

The insertion algorithm is implemented as:

Implementation : Insertion

Insertion(int a [], int *m, int n, int pos, int item)


/* Here m is passed by reference as its value changes after the insertion of new element */
{
int j;

if (pos >0 && pos <n)


{
7
Chapter-2 Arrays

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.");
}
}

Let us put this idea into a program.

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>

const int n = 20;


main()
{
int a[n];
int i,m, item, pos;
printf("\nEnter number of elements < 20 - ");
scanf("%d", &m);
if (m>n)
{
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 the position of new item - ");
scanf("%d", &pos);
printf("Please enter new element - ");
scanf("%d", &item);
Insertion(a, &m, n, pos, item); /* Calling Insertion function */
for(i=0;i<m;i++)
printf("\n%d", a[i]);
}
Insertion(int a [], int *m, int n, int pos, int item)
8
Chapter-2 Arrays

{
int j,temp;

if (pos >0 && pos <n)


{
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("\nPosition out of dimension.");
printf("\nPlease enter correct dimension.");
}
}

The output of this program is as….

Enter number of elements < 20 – 5


Please enter 5 elements:
12
34
27
54
70

Please enter the position of new item – 4


Please enter new element – 66

Item is inserted successfully.


12
34
27
66
54
70

Deleting an Element from One Dimensional Array

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

Here is the deletion algorithm.

Algorithm : Deletion

Deletion (A, M, Pos)


Here A is an array, M is number of elements present in an array and Pos is
the location of data item to be deleted.

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

The deletion algorithm is implemented as:


Implementation : Deletion
Deletion (int a[ ], int *m, int pos)
/* Here m is passed by reference as its value changes after the deletion of element */
{
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”);

}
10
Chapter-2 Arrays

Let us put this idea into a program.

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");

The output of this program is as….

Enter number of elements < 20– 5


Please enter 5 elements:
12
34
27
54
70

Please enter position of the item you want to delete – 4


Deleted item = 54
11
Chapter-2 Arrays

Array after deletion is as:


12
34
27
70

Two Dimensional Arrays


Two-dimensional arrays are useful for representing games like chess, tic-tac-toe, or Scrabble.
The two-dimensional array is declared as:

datatype arrayname [rows] [columns]

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];

Accessing Two-dimensional Array Elements

An element in a two-dimensional array is accessed by specifying the respective row and


column numbers in it. Thus each element is accessed by a pair of subscripts which represent
the element’s position within each dimension. Each subscript has its own set of braces. Let
you want to refer an element which is at i th position in a row and jth position in a column of
array ‘a’ then we use the notation - a[i][j]. For example

a[2][4]

would refer to the integer value in the third row and the fifth column.

Reading and Writing Two-dimensional Arrays

We can enter data into an using a nested for loop as:

for(int i=0; i<4; i++)


for(intj=0; j<j; j++)
scanf(“%d”, &a[i][j]);

Similarly we can read back data from a two-dimensional array by using a nested for loop as:

for(int i=0; i<4; i++)


for(intj=0; j<j; j++)
printf(“%d”, a[i][j]);

Initializing a Two-dimensional Arrays

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

Representation of Two Dimensional Array

Basically there are two types of representation of two-dimensional array:

(a) Row major order


(b) Column major order

Row major order

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.

Figure 2.4 shows the row major order of (3 * 4) matrix.

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

0th Row 1st Row 2nd Row

Figure-2.4 Row Major Order Representation

In general for an array A[M, N], the address of element A[I, J] is:

A[ I,J ] ( Address of [I, J] ) = Base address + w ( I x N + J)

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

Address of A [2][1] = 64080 + 4 (2x5+1)


= 64080 + 4 (11)
= 64124

Column major order

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.

Figure 2.5 shows the row major order of (3 * 4) matrix.

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

0th Col 1st Col 2nd Col 3rd Col

Figure-2.4 Column Major Order Representation

The basic formula for calculating the address of element A[I, J] in an array of (M x N) elements
in column order as :

A[ I,J ] ( Address of [I, J] ) = Base address + w ( J x M + I)

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

Address of A [2][1] = 64080 + 4 (4x2+1)


= 64080 + 4 (9)
= 64116

Operation performed on Two Dimensional Arrays


The two-dimensional array is also referred as a matrix. As you pass single dimensional array,
you can pass two dimensional arrays to a function. When you pass single dimensional array to
a function then the declaration of the dimension with array name in a function definition is
optional. But in two dimensional arrays, the declaration of number of rows is optional, but the
declaration of number of columns is compulsory. Thus when you pass a two dimensional array
‘a’ of size (3 x 3) as:

ReadMatrix(a, 3, 3);

The declaration of number of columns with array name ‘a’ is compulsory in function definition
of ReadMatrix ‘a’ as:

compulsory

ReadMatrix(int a[ ][3], int row, int col)


{
/* …. */
optional
}

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

Cij = [A+B]ij = Aij + Bij


14
Chapter-2 Arrays

For example, if we have

4 5 7 2 5 6

A = 9 1 2 B= 8 7 2

10 5 2 1 3 4

4+2 5+5 7+6

A + B = 9+8 7+1 2+2

10+1 5+3 2+4

6 10 13

A + B = 17 8 4

11 8 6

The algorithm of performing addition operation on matrixes A & B is implemented as:

Algorithm : AddMatrix

AddMmatrix (A, Row1, Col1, B, Row2, Col2, C)


Here ‘A’ and ‘B’ matrices are of sizes (Row1 x Col1) and (Row2 x
Col2) respectively and C is the resultant matrix.

1. Check whether both matrices are equal in dimensions or not.


2. If ((Row1== Row2) And (Col1==Col2)) then go to Step 3
otherwise go to Step 10
3. Initialize I = 0
4. Repeat through Step-9 while (I < Row1)
5. Initialize J = 0
6. Repeat through Step-8 while (J < Col1)
7. Compute C[I][J] = A[I][J] + B[I][J]
8. Increment the value of J as J = J + 1
9. Increment the value of I as I = I +1
10. Exit

Here is the implementation of 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

}
}

Let us put this idea into a program.

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]);
}

printf(“\nEnter the dimension of second matrix :”);


scan(“%d %d”, &r2, &c2);
printf(“\nEnter the elements of first matrix :\n”);
for (i=0; i<r2; i++)
{
for (j=0; j<c2; j++)
scanf(“%d”, &b[i][j]);
}
AddMmatrix (a, r1, c1, b, r2, c2, c);

printf(“\nAfter addition of two matrices - \n”)


for (i=0; i<r1; i++)
{
printf(“\n”);
for (j=0; j<c1; j++)
printf(“%d\t”, c[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

For example, if we have

4 5 7 2 5 6
A = B=
9 1 2 8 7 2

10 5 2 1 3 4

4*2+5*8+7*1 4*5+5*7+7*3 4*6+5*2+7*4

A x B = 9*2+1*8+2*1 9*5+1*7+2*3 9*6+1*2+2*4

10*2+5*8+2*1 10*5+5*7+2*3 10*6+5*2+2*4

55 76 62

A x B = 28 58 64

62 91 78

The algorithm of performing multiplication operation on matrixes A & B is implemented as:

Algorithm : MultMatrix

MultMmatrix (A, Row1, Col1, B, Row2, Col2, C)


Here ‘A’ and ‘B’ matrices are of sizes (Row1 x Col1) and (Row2 x Col2)
respectively. And C is the resultant matrix.

1. Check whether both matrices can be multiplied or not.


2. If (Col1== Row2) then go to Step 3; Otherwise go to Step 14
3. Initialize I = 0
4. Repeat through Step-13 while (I < Row1)
5. Initialize J = 0
6. Repeat through Step-12 while (J < Col2)
7. Set C[I][J] = 0
8. Initialize k = 0
9. Repeat through Step-11 while (J < Col1)
10. Compute C[I][J] = C[I][J] + A[I][J] * B[I][J]
11. Increment the value of K as K = K + 1
12. Increment the value of J as J = J + 1
13. Increment the value of I as I = I +1
14. Exit

Here is the implementation of 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]);
}

printf(“\nEnter the dimension of second matrix :”);


scan(“%d %d”, &r2, &c2);
printf(“\nEnter the elements of first matrix :\n”);
for (i=0; i<r2; i++)
{
for (j=0; j<c2; j++)
scanf(“%d”, &b[i][j]);
}
MultMmatrix (a, r1, c1, b, r2, c2, c);

printf(“\nAfter multiplication of two matrices - \n”)


for (i=0; i<r1; i++)
{
printf(“\n”);
for (j=0; j<c2; j++)
printf(“%d\t”, c[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

printf (“\nMultiplication not possible. Number of columns of first matrix is not


equal to number of rows of second matrix”);
getch ();
exit (0);
}
}

Transpose of a Matrix

Let we have a matrix A of size (m * n). The transpose of A, written as A T, is obtained by


interchanging the rows with corresponding columns of a matrix A. For example, if we have

4 5 7

A = 9 1 2

10 5 2

4 9 10

AT = 5 1 5

7 2 2

The ijth element of B is given by - Bij = Aji

The algorithm of performing transpose of a given on matrix A is as:

Algorithm : Transpose

Transpose (A, Row1, Coll1, B)

Here A is a matrix of having Row1 and Col1 number of rows and


number of columns respectively.

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

Here is the implementation of this algorithm.

Implementation : Transpose

Transpose (int a [10][10], int row1, int col1, int b [10][10],)


{
int i, j;
for (i=0; i<row1; i++)
{
for (j=0; j<col1; j++)
b [i][j] = a[j][i];
}
}

Dynamic Memory Allocation and Deallocation


Array is a static data structure because we can not change the size of an array in the mid of
the program. It means that if we declare an array of 50 elements then we can store at most 50
19
Chapter-2 Arrays

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.

Static memory allocation – a process in which the memory is allocated during


compile time
dynamic memory allocation – a process in which the memory is allocated during
run (execution) time

The malloc() and calloc() Functions

C provides two library functions malloc () and calloc () to created memory during run time.
The syntax of using malloc () and calloc () function is as:

malloc (totalsize); /* allocates totalsize number of bytes */


calloc (n, size); /* allocates n * size number of bytes */

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:

 malloc (40); /* 20 is total integers and 2 number of bytes reserved by


each integer. So 20*2 = 40 must be reserved */

 calloc (20, 2); /* 20 is total integers and 2 number of bytes reserved by


each integer. */

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.

Program-chap0210.c illustrates this concept by using malloc() function.

/* Program – chap0210.c : Use of malloc () */


#include <stdio.h>
#include <alloc.h>
main ()
{
int *iptr, i, num1;
float num2, *fptr ;
printf (“\n How many integers you want to create dynamically? ”);
scanf (“%d”, &num1);

iptr = malloc (num1*2);

printf (“\n Please enter %d integer values –”, num1);


for (i=0; i<num1; i++)
scanf (“%d”, iptr+i);

printf (“\n How many real number you want to create dynamically? ”);
scanf (“%f”, &num2);
20
Chapter-2 Arrays

fptr = malloc (num2*4);

printf (“\n Please enter %d real values –”, num2);


for (i=0;i<num2; i++)
scanf (“%f”, fptr+i);

printf (“\n You have entered these integer values\n”);


for (i=0; i<num1; i++)
printf (“\n%d”, *(iptr+i));

printf (“\n You have entered these real values\n”);

for (i=0;i<num1; i++)


printf (“\n%f”, *(fptr+i));
getch ();
}

The output of this program is as:

How many integers you want to create dynamically? 5


Please enter 5 integer real values – 10 22 53 14 85

How many real number you want to create dynamically? 4

Please enter 4 real values – 1.1 2.2 3.3 4.4

You have entered these integer values


10
22
53
14
85

You have entered these real values


1.100000
2.200000
3.300000
4.400000

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 */
….

Similarly you can releases the memory as:

free(mptr1);
free(mptr2);
21
Chapter-2 Arrays

Now let us see a simple program that multiples two matrices using pointer notations.

Program-2.11 : Write a program which multiplies two matrices using pointers.

#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);
}

int *mptr1 = malloc(row1*col1* sizeof(int));


int *mptr2 = malloc((row2 * col2 * sizeof(int));
int *mptr3 = malloc[(row2 * col1 * sizeof(int));

printf("\nEnter elements of matrix-1.");


for(i=0; i<row1; i++)
{
for(j=0; j<col1; j++)
scanf(“%d”, mptr1[i*col1+j]);
}

printf("\nEnter elements of matrix-2.");


for(i=0; i<row2; i++)
{
for(j=0; j<col1; j++)
scanf(“%d”, mptr1[i*col2+j]);
}

for(i=0; i<row1; i++)


{
for(j=0; j<col2; j++)
{
mptr3[i*col2+j] = 0;
for(k=0; k<col1 ; k++)
mptr3[i*col2+j] += mptr1[i*col1+k]*mptr2[k*col2+j];
}
}

printf( "\nMultiplication of two matrices is as.\n");


for(i=0; i<row1; i++)
{
printf("\n");
for(j=0; j<col2; j++)
cout << mptr3[i*col2+j] << "\t";
}
}

When you run this program you get following output….

Enter number of rows of matrix-1 = 3


Enter number of columns of matrix - 1 = 4
Enter number of rows of matrix - 2 = 4
22
Chapter-2 Arrays

Enter number of columns of matrix - 2 = 3

Enter elements of matrix-1.


1111
2222
3333

Enter elements of matrix-2.


111
222
333
444

Multiplication of two matrices is as.

10 10 10
20 20 20
30 30 30

Similarly using pointer notations you can subtract and multiply two matrices.

You might also like