You are on page 1of 30

Arrays-I

9
(Numeric Arrays)

Chapter Outline
“There are basically two types of people. People
who accomplish things and people who claim to 9.1. Introduction.
have accomplished things. The first group is less 9.2. Types of arrays.
crowded.” -Mark Twain
9.3. One-Dimensional
array.
9.4. Operations on one-
dimensional array.
9.5. Two-Dimensional
“We must remember that one determined array.
person can make a significant difference, and
9.6. Passing array as an
that a small group of determined people can
change the course of history.” -Sonia Johnson argument to a
function.
9.7. Conclusion.

“The greater the loyalty of a group toward the


group, the greater is the motivation among the
members to achieve the goals of the group, and
the greater the probability that the group will
achieve its goals.” -Rensis Likert
9.1. Introduction
For understanding the concept of arrays, let us consider an example:
#include<stdio.h>
main()
{
int a;
a=10;
a=20;
a=30;
printf(“%d%d%d”,a,a,a);
}
This program prints the values 30, 30 and 30 instead of 10, 20 and 30. In this program, we can observe
that “a“ is a variable that holds only one value at a time. But, we require a special type of variable that
holds more than one value of same type at a time, referred by same name. Here, the concept of arrays
comes into picture.
Suppose, we wish to arrange the percentage marks obtained by 100 students in ascending order. In
such a case we have two options to store these marks in memory:
a) Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each
variable containing one student’s marks.
b) Construct one variable (called array or subscripted variable) capable of storing or holding all the
hundred values.
Obviously, the second alternative is better. A simple reason for this is, it would be much easier to handle
one variable than handling 100 different variables.
Therefore,

An array is finite homogeneous collection of elements stored in contiguous memory locations


referred by same name.

This definition has the following parts:


 Array consists of homogenous collection of elements. That is, all the data items stored in array are
of same type.
 All elements are stored in contiguous locations. That is, all elements are stored one after other in
successive locations of memory (based on size of type of data items). Of course, fixed amount of
memory is allocated to an array.
 All elements refer to same name. That is, each element can be identified with the same name
including different index value (subscript value). Hence, an array is also called as a subscripted
variable. By using, these index values, an element in the array can be accessed directly.

Variables are like individual folders, whereas an array is like a single folder with many compartments.
As an array is collection of elements, the total count of elements in it should be specified with a non-
negative integer with in square brackets [], placed after the array name. E.g., a[10] is an array that has
the capability of holding 10 elements.
9.2. Types of arrays
Based on type of values being hold, arrays are broadly classified into two categories:
a) Numeric array: An array that consists of elements of numeric type; whether they are integers or
floating-point values.
b) Non-numeric array: An array that consists of elements of type char. These non-numeric arrays are
also called as strings.

An array’s name should be followed by square brackets. These square brackets are used to specify the
total number of elements present in that array. Based on number of square brackets (subscripts or
dimensions), arrays are broadly classified into two categories:
I. One-dimensional arrays.
II. Multi-dimensional arrays.
One-dimensional array consists of only one subscript. Multi-dimensional arrays consist of more than one
subscript. E.g., two-dimensional array consists of 2 subscripts; 3-dimensional array consists of 3
subscripts and so on. Usually, one-dimensional numeric array consists of numbers as individual elements
where as multi-dimensional numeric array consists of arrays as individual elements. Hence, multi-
dimensional array is also called as array of arrays.

9.3. One-Dimensional array


9.3.1. Declaring one-dimensional array:
Just like an ordinary variable, an array should be declared before it is used.
A one-dimensional array can be declared as follows:
<storage class> <data type> <array_name>[size];
In this syntax,
<storage class> is any one of auto, static, extern or register. It specifies the storage location of an array,
the default values of all elements, scope and life time of an array.
<data type> is any basic data type such as int, float, char or double or any derived data type such as long
int, short int and so on.
<array_name> is any valid identifier.
Size is any non-negative integer constant or integer expression.
1. int a[20]; // one-dimensional array capable of holding 20 elements of type int
2. # define MAXSIZE 30
float b[MAXSIZE]; //1-D array capable of holding 30 elements of type float
3. int k=20;
int c[k]; //Error: Array size can’t be declared as a variable.
9.3.2. Initializing one-dimensional array:
Initializing One-dimensional array is the process of assigning values to its all contiguous locations or to
some of them with some initial values for avoiding garbage values those are already in it. It can be
directly done with the help of assignment operator.
A one-dimensional array is initialized as follows: array declaration follows assignment operator and a list
of values that are separated by commas enclosed with in curly braces. This process is also called as
“initialization at compile-time”.
Ex: int a[7]={12,45,54,2,87,76,3};
Once the above array gets initialized, the memory map for it will be as follows:

a[0] a[1] a[2] a[3] a[4] a[5] a[6]


12 45 54 2 87 76 3

1000 1002 1004 1006 1008 1010 1012

From this memory map, we can observe that an array subscript value (or index) starts from 0 and ends
with n-1, where n is the size of the array. Usually, the first element’s location is called the base address of
the array. Each element is uniquely identified with the help of array name and its subscript value – 1 or
base address+ (pos-1) * sizeof(type). . e.g., 4th element of array ‘a’ is identified with a[3] or 1000+(4-
1)*2=1006.
9.3.3. Reading and printing one-dimensional array:
A One-Dimensional array’s locations can be filled with input values from keyboard with the help of scanf()
statement. Because an array consists of more than one element, we should require a loop counter for
keeping track of index values. The loop counter is always an integer value that begins with 0 and ends
with n-1. The loop counter should be incremented by 1 for keeping track of next immediate indexes. For
each indexed element, scanf() statement expects an input value from programmer. This process can be
depicted with the help of the following statement:
for(i=0;i<n;i++) // i: loop counter
scanf(“%d”,&a[i]);
The above statement first reads a[0], then a[1], a[2], a[3]…and so on. This process is also called as
“initialization at run-time”.
Once an array is read, it can be accessed directly or sequentially with the help of printf()
statement. If we want an element at particular position, then we should give the following argument to
printf() : a[position-1]. E.g., we want the element at 5 th position, then we should give a[4] to printf()
statement:
printf(“Element at 5th position is %d”,a[4]);
If we want to access all the elements in the array sequentially, then we can use printf() statement along
with a loop as follows:
printf(“\n The array elements are:”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
/*Program to calculate sum and average /*Program to calculate Biggest and
of n numbers*/ smallest of n numbers*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a[10],n,i; int a[10],n,i,big,small;
float avg,sum;
printf(“\n Enter the array size:”); printf(“\n Enter the array size:”);
scanf(“%d”,&n); scanf(“%d”,&n);
sum=0.0; printf(“\n Enter the array elements:”);
printf(“\n Enter the array elements:”); for(i=0;i<n;i++)
for(i=0;i<n;i++) scanf(“%d”,&a[i]);
{
scanf(“%d”,&a[i]); big=small=a[0];
sum=sum+a[i]; for(i=1;i<n;i++)
} {
printf(“\n Sum=%d”,sum); if(a[i]>big)
avg=(float)sum/n; big=a[i];
printf(“\n Average=%f”,avg); if(a[i]<small)
} small=a[i];
}
printf(“\n Biggest number=%d”,big);
printf(“\n Smallest number=%d”,small);
}
/*program to calculate mean, variance /*Program to calculate second Biggest
and standard deviation*/ and second smallest of n numbers*/
#include<stdio.h> #include<stdio.h>
#include<math.h> main()
main() {
{ int a[10],n,i,j,k,temp;
int a[10],n,i; printf(“\n Enter the array size:”);
float mean,sum,sumsq,std,variance; scanf(“%d”,&n);
printf(“\n Enter the array size:”); printf(“\n Enter the array elements:”);
scanf(“%d”,&n); for(i=0;i<n;i++)
sum=0.0; scanf(“%d”,&a[i]);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++) /*for removing duplicate elements*/
{ for(i=0;i<n-1;i++){
scanf(“%d”,&a[i]); for(j=i+1;j<n;j++){
sum=sum+a[i]; if(a[i]==a[j]){
} for(k=j;k<n-1;k++)
mean=sum/(float)n; a[k]=a[k+1];
n=n-1;
for(i=0,sumsq=0.0;i<n;i++) j=j-1;
sumsq=sumsq+(mean-a[i])*(mean-a[i]); }
}
variance=sumsq/(float)n; }
std=sqrt(variance); /* sorting*/
printf(“\n Mean=%f”,mean); for(i=0;i<n-1;i++)
printf(“\n variance=%f”,variance); for(j=i+1;j<n;j++)
printf(“\n standard deviation=%f”,std); if(a[i]>a[j]){
} temp=a[i];
a[i]=a[j];
a[j]=temp;
}
printf(“\n Second biggest=%d”,a[n-2]);
printf(“\n Second smallest=%d”,a[1]);}
9.4. Operations on arrays
An array is an Abstract Data Type (ADT). An ADT is a collection of data and operations on that data. As an
ADT, the data an array includes is the collection of data items (integers, decimal points, characters or
strings). The operations on these data items include:
Traversing: Visiting each element at least once.
Reversing: Changing the positions of elements.
Insertion: Inserting a new data item into existing list of data items
Deletion: Deleting a data item from existing list of data items.
Searching: Searching for a particular data item in the list of data items.
Sorting: Arranging the list of data items in ascending order.
Merging: Combining sorted arrays into one sorted array.

9.4.1. Traversing an array


Traversing is the process of visiting each element of the array. An array’s first element’s index is called
the Lower Bound (LB) and the last element’s index is called the Upper Bound (UB). Traversing is the
process of reaching Upper Bound starting from Lower Bound, incrementing Lower Bound by 1 each time.

The following program demonstrates this:


/* A program to traverse an array*/
#include<stdio.h>
main()
{
int a[10],n,LB,UB;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
LB=0;
UB=n-1;
printf(“\n Enter array elements:”);
for(i=LB;i<UB;i++)
scanf(“%d”,&a[i]);
printf(“\n The array elements are:”);
for(i=LB;i<UB;i++)
printf(“%d\t”,a[i]);
}

Interview question #1
What is meant by bounds checking?
Bounds checking is the process of verifying whether the accessed array element is in bounds or not.
An array has two bounds: lower bound (0) and upper bound (n-1). While accessing an array, it is
important to access the elements only within bounds. Some language compilers check the bounds. If
we try access out of bounds, then there will be runtime errors. C compiler allows us to access elements
out of bounds, since there is no bounds checking concept in C. It is suggested that access each element
in an array within bounds.
9.4.2. Reversing an array
Reversing is the process of changing positions of elements in actual array to get reversed order of
elements. To reverse an array, we should interchange the elements a[0] with a[n-1], a[1] with a[n-2],
a[2] with a[n-3] and so on. For reversing the contents of an array, we use two loop counters; one for
keep tracking the values of 0,1,2…so on and the other for keep tracking the values of n-1, n-2,n-3… and
so on. By using these loop counters, we can interchange the elements.

The following program demonstrates this:


/* A program to reverse an array*?
#include<stdio.h>
main()
{
int a[10],n,i,j;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
for(i=0,j=n-1;i<j;i++,j--)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
printf(“\n The reversed array is:”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}
9.4.3. Inserting an element into an array
Insertion is the process of inserting a new element into an existing array. This insertion process can best
be explained with the following example:
Let us consider an array that has the following memory map:

10 9 12 76 45

a[0] a[1] a[2] a[3] a[4]


To insert an element 89 into an array at 3rd position do the following:
1) First, increment the current length of array by 1. e.g., the above array holds 5 elements, then
increment 5 by 1. Then we get an array with 6 elements as given below

10 9 12 76 45

a[0] a[1] a[2] a[3] a[4] a[5]

2) Second, move all the elements to their next locations starting from 3 rd position until the end of array
is reached. This process is depicted as follows:

Iteration #1 10 9 12 76 45 45

Iteration #2 10 9 12 76 76 45

Iteration #3 10 9 12 12 76 45

a[0] a[1] a[2] a[3] a[4] a[5]


3) Finally, insert the new element at the specified 3 rd position. i.e, assign the value 89 to a[2]. In other
words, a[2]=89. Hence the new array looks like this:

10 9 89 12 76 45

a[0] a[1] a[2] a[3] a[4] a[5]


The following program demonstrates this process:
#include<stdio.h>
main()
{ int a[10],n,i,pos,ele;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n Enter the element to insert:”);
scanf(“%d”,&ele);
printf(“\n Enter the position:”);
scanf(“%d”,&pos);
n=n+1; //step 1
for(i=n-1;i>=pos-1;i- -) //step 2
a[i]=a[i-1];
a[pos-1]=ele; //step3
printf(“\n New Array\n”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}
9.4.4. Deleting an element from an array
Deletion is the process of removing an existing element from an array. The deletion process can best be
explained with the following example:

10 9 12 76 45

a[0] a[1] a[2] a[3] a[4]


Suppose, we want to delete the element at 3rd position, then do the following:
1) First, pick up the element at the specified position. In other words, assign the value at a[pos-1] to
a variable. Therefore, ele=a[2];
2) Move all the elements after the element at specified position to their previous immediate locations
till the end of the array is reached.

Iteration #1 10 9 76 76 45

Iteration #2 10 9 76 45 45

3) As the deletion of an element decreases the size of array, decrease the current length of array by1.
Hence the length of array now becomes 4. Now, the array looks like this:

10 9 76 45

a[0] a[1] a[2] a[3]


The following program demonstrates the process of deletion:
#include<stdio.h>
main()
{
int a[10],n,ele,pos,i;
printf(“\nEnter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n Enter the position:”);
scanf(“%d”,&pos);
printf(“\n The deleted element=%d”,a[pos-1]); //step-1
for(i=pos-1;i<n;i++) //step-2
a[i]=a[i+1];
n=n-1;
printf(“\n New array:”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}
10

9.4.5. Searching an element from an array

Searching is the process of finding location of an element in the given array. There are two basic methods
of locating an element:
1. Linear Search
2. Binary Search
Linear Search (or) Sequential Search:
This method works on the following principle: “ Compare each element of array with the element to be
searched. If suitable match is found, then return the position by leaving next comparisions; otherwise,
leave the proper message to the programmer after the end of the array gets reached.”
This method can best be explained with the following example:
Suppose that there is an array with the following memory map:

12 45 54 2 87 76 3

a[0] a[1] a[2] a[3] a[4] a[5] a[6]

Let the element to be searched be 87. Then, Linear search works as follows:
87

Iteration #1: a[0] is compared with


searching element. Not suitable
12 45 54 2 87 76 3 match. Proceed further.

87

Iteration #2: a[1] is compared with


searching element. Not suitable
12 45 54 2 87 76 3 match. Proceed further.

87

Iteration #3: a[2] is compared with


searching element. Not suitable
12 45 54 2 87 76 3 match. Proceed further.

87

Iteration #4: a[3] is compared with


searching element. Not suitable
12 45 54 2 87 76 3 match. Proceed further.
87

Iteration #5: a[4] is compared with


searching element. suitable match.
12 45 54 2 87 76 3 Therefore, Pos=4+1=5

a[0] a[1] a[2] a[3] a[4] a[5] a[6]

The following program demonstrates Linear Search:


#include<stdio.h>
main()
{
int a[10],n,i,ele,pos,flag;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n Enter the element to be searched:”);
scanf(“%d”,&ele);
flag=0;
for(i=0;i<n;i++)
{
if(a[i]= =ele)
{
flag=1;
pos=i+1;
break;
}
}
if(flag= =1)
printf(“\n The given element is found at %d position”,pos);
else
printf(“\n The given element is not found”);
}

Binary Search: When the input elements’ list is in sorted order, there is more efficient way to search
through it than looking at each element from beginning. This method is known as binary search.
The pre-requisite for binary search method is that the input elements’ list is in the sorted order.
The method starts with looking at the middle element of the list. If it matches with the search key, then
the search is completed. Otherwise, the search key may be in upper half or in lower half. The search
progresses through the upper half, if the search key is greater than the middle element or through the
lower half, if the search key is lesser than the middle element. The process is continued until the search
key is found or when the portion of the sub-list to be searched is empty.
This binary search method follows divide-and-conquer approach. By using this approach, the sorted
list will be divided into sub-lists. Each sub-list, in turn, will be divided into sub-lists till the search key is
found or there are no elements in the sub-list.
Ex: Let us consider an array (in sorted order) that consists of the following elements to search element
87:
Iteration #1
2 3 12 45 54 76 87 mid=(low+high)/2
=(0+6)/2
=3
low=0 mid=3 high=6

Since ele>a[mid], process right half. Then change low=mid+1 and calculate new middle position.

2 3 12 45 54 76 87
Iteration#2
mid=(low+high)/2
=(4+6)/2
low=4 high=6 =5

mid=5

Since ele>a[mid], process right half. Then change low=mid+1 and calculate new middle position.

low=6 Iteration#3
mid=(low+high)/2
=(6+6)/2
2 3 12 45 54 76 87 =6

mid=6 high=6

Since ele==a[mid], the element is found at mid+1 position. i.e., the element is found at 7th position.

The Binary search method can be implemented either iteratively or recursively.

Iterative approach: The iterative approach progresses through by defining 3 variables: lower bound,
upper bound and middle position of search list that contain the search key.
 If the search key and search list’s element are equal, then the search is completed and the middle
position will be taken into count.
 If the search key is lesser than the middle element of array, then the search key must be in lower
half of that array. So, set the upper bound to one less than the middle position.
 If the search key is greater than the middle element of array, then the search key must be in upper
half of that array. So, set the lower bound to middle position plus 1.
This iterative process stops when either 1) the search key is found or 2) the search sub-list becomes
empty.
The following program demonstrates iterative process of binary search:
#include<stdio.h>
main()
{
int a[10],n,low,high,mid,ele,pos,i,flag;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n Enter the element to be searched:”);
scanf(“%d”,&ele);
low=0;
high=n-1;
flag=0;
while(low<=high)
{
mid=(low+high)/2;
if(ele= =a[mid])
{
flag=1;
pos=mid+1;
break;
}
else if(ele>a[mid])
low=mid+1;
else
high=mid-1;
}
if(flag= =1)
printf(“\n The element is found at %d position”,pos);
else
printf(“\n The element is not found”);
}

Recursive approach: The recursive approach of binary search procedure is relatively easy. It differs from
the iterative approach mainly in that it requires the upper bound and lower bound indices be passed as
arguments.
The recursive function determines whether the search key lies in the lower half or upper half of the
array, then calls itself on the appropriate half. The termination conditions or base cases are:
 If low>high, then the partition (sub-list) to be searched has no elements in it and
 If there is a match with the element in the middle of the current partition, then we can return that
middle position immediately.
There is no particular advantage in applying recursion in binary search of an array. In fact, from a
processing stand point, the iterative approach is likely to be more efficient.
The following program demonstrates the recursive approach of binary search:
#include<stdio.h>
int binarysearch(int[],int,int,int);
main()
{
int a[10],n,ele,pos,high;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n Enter the element to be searched:”);
scanf(“%d”,&ele);
low=0;
high=n-1;
pos=binarysearch(a,ele,low,high);
if(pos<0)
printf(“\n The element is not found”);
else
printf(“\n The element is found at %d position”,pos+1);
}
int binarysearch(int a[],int ele,int low,int high)
{
int mid;
if(low>high)
return (-1);
mid=(low+high)/2;
if(ele= =a[mid])
return (mid);
else if(ele>a[mid])
binarysearch(a,ele,mid+1,high);
else
binarysearch(a,ele,low,mid-1);
}

9.4.6. Sorting elements of an array


Let A be list of N numbers. Sorting A refers to the operation of rearranging the elements of A so that they
are in increasing order. i.e., A[0]<A[1]<A[2]<………..<A[N-1]. There are 3 basic sorting methods:
1. Selection sort
2. Bubble sort
3. Insertion sort

Selection sort: Suppose an array A with N elements A[0], A[1]……..A[N-1] is in memory. Then in
selection sort, first find the smallest element in the list and put it in first position (i.e., at A[0]). Later, find
the second smallest element in the list and put it in second position (i.e., at A[1])…. and so on.
The selection sort method is carried out like this:
Pass 1: Find the location MINPOS the smallest element in the list of n elements:
A[0],A[1],A[2]…A[n-1]. After then, interchange A[MINPOS] and A[0]. Now,
observe that A[0] is sorted.
Pass 2: Find the location MINPOS of the smallest element in the sub-list of n-1 elements:
A[1],A[2],A[3]…A[n-1]. After then, interchange A[MINPOS] and A[1]. Now,
observe that A[0] and A[1] are sorted, since A[1]<=A[0].
Pass 3: Find the location MINPOS of the smallest element in the sub-list of n-2 elements:
A[1],A[2],A[3]…A[n-1]. After then, interchange A[MINPOS] and A[1]. Now,
observe that A[0] and A[1] are sorted, since A[1]<=A[0].
…….
…….
Pass n-1: Find the location MINPOS of the smaller of the elements A[n-2] and A[n-1]. After
then, interchange A[MINPOS] and A[n-2]. Now, observe that A[0], A[1],A[2]… A[n-
1] are sorted, since A[n-2]<=A[n-1].
Ex: suppose an array A consists of 8 elements as follows:

77 33 44 11 88 22 66 55
The following program demonstrates the selection sort technique:
#include<stdio.h>
main()
{
int a[10],i,j,temp,minpos,n;
printf("\n Enter the array size:");
scanf("%d",&n);
printf("\n Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

for(i=0;i<n-1;i++)
{
minpos=i;
for(j=i+1;j<n;j++)
if(a[j]<a[minpos])
minpos=j;
if(minpos!=i)
{
temp=a[i];
a[i]=a[minpos];
a[minpos]=temp;
}
}
printf("\n Array elements after sorting (Selection sort):");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

Bubble Sort: The bubble sort is the oldest and simplest sort in use. Unfortunately, it's also the slowest.
The bubble sort works by comparing each item in the list with the item next to it, and swapping them if
required. This process gets repeated until there is a pass all the way through the list without swapping any
items (in other words, all items are in the correct order). This causes larger values to "bubble" to the end
of the list while smaller values "sink" towards the beginning of the list. The following example best
explains the concept of bubble sort:

Let A be an array with the following memory map:

77 33 44 11 88 22 66 55
The following code demonstrates the bubble sort technique:
#include<stdio.h>
main()
{
int a[10],n,i,j,temp;
printf("\n Enter the array size:");
scanf("%d",&n);
printf("\n Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n Array elements after sort (Bubble sort):");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

Insertion sort: Suppose that there is an array A with N elements A[0], A[1], A[2]……..A[N-1]. The
insertion sort method scans A from A[0] to A[N-1], inserting each element A[k] into its proper position in
the previously sorted sub array A[0], A[1], A[2]…….A[k-1]. The insertion method is carried out like this:

Pass 1: A[0] by itself is trivially sorted.


Pass 2: A[1] is inserted either before A[0] or after A[0] so that A[0] and A[1] are sorted.
Pass 3: A[2] is inserted into its proper place in A[0] and A[1]. That is, A[2] can be inserted
before A[0] or in between A[0] and A[1] or after A[1] so that A[0],A[1] and A[2]
are in sorted order.
Pass 4: A[3] is inserted into its proper place in A[0],A[1],A[2] so that A[0],A[1],A[2],A[3]
are in sorted order.
…….
…….
Pass n: A[n-1] is inserted into proper place in A[0],A[1],A[2]…A[N-1] so that
A[0],A[1],A[2],…,A[N-1] are in sorted order.

In this technique, we insert an element A[k] in sub array A[0],A[1]…A[k-1]. This can be accomplished by
comparing A[k] with A[k-1], A[k-2],A[k-3]… and so on until first meeting an element A[j] such that
A[j]<=A[k]. Then each of elements A[k-1], A[k-2] …….A[j+1] is moved forward to one location and A[k]
is inserted at j+1st position.

Ex: Let A be an array with the following memory map:


77 33 44 11 88 22 66 55
#include<stdio.h>
main()
{
int a[10],n,i,j,temp;
printf("\n Enter the array size:");
scanf("%d",&n);
printf("\n Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
temp=a[i];
j=i;
while(j>0&& temp<a[j-1])
{
a[j]=a[j-1];
j=j-1;
}
a[j]=temp;
}
printf("\n Sorted list (Insertion sort):");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
9.4.6. Merging arrays into one array
Merging is the process of combining two or more sorted arrays into one sorted array. Suppose that there
are two sorted arrays: A with N elements and B with M elements. Then the merged array consists of N+M
elements or less, if there are duplicate elements in both.
The following program best explains the concept of merging two arrays:
/* Merging two arrays into one array*/
#include<stdio.h>
main()
{
int a[10],n,b[10],m,c[20],i,j,k,l;
printf(“\n Enter the first array size:”);
scanf(“%d”,&n);
printf(“\n Enter the first array elements in sorted order:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);

printf(“\n Enter the second array size:”);


scanf(“%d”,&m);
printf(“\n Enter the second array elements in sorted order:”);
for(j=0;j<m;j++)
scanf(“%d”,&b[j]);
i=j=k=0;
while(i<n&&j<m)
{
if(a[i]<b[j])
{
c[k]=a[i];
i++; k++;
}
else if(a[i]>b[j])
{
c[k]=b[j];
j++; k++;
}
else
{
c[k]=a[i];
i++;j++;k++;
}
}
if(i<n)
{
for(l=0;l<n;l++)
{
c[k]=a[l];
k++;
}
}
if(j<m)
{
for(l=0;l<m;l++)
{
c[k]=b[l];
k++;
}
}

printf(“\n The merged list:”);


for(i=0;i<k;i++)
printf(“%d\t”,c[i]);’
}
9.5. Two-Dimensional arrays
A Two-Dimensional array looks like array name followed by two subscripts. It is very helpful to represent
matrices in mathematics or tables in business. The first subscript is used to denote the Number of rows
and second is used to denote the number of columns. The total number of elements a two-dimensional
array holds is the product of values of both subscript values.

9.5.1. Declaring Two-Dimensional array:


Just like an ordinary variable, an array should be declared before it is used.
A two-dimensional array can be declared as follows:
<data type> <array_name>[row][column];
In this syntax,
<data type> is any basic data type such as int, float, char or double or any derived data type such as long
int, short int and so on.
<array_name> is any valid identifier.
row and column values are any non-negative integer constants or integer expressions.
Ex: int a[5][3]; // two-dimensional array capable of holding 15 (5*3) elements of type int
# define ROW 10
# define COLUMN 5
float b[ROW][COLUMN]; //2-D array capable of holding 15 elements of type float

9.5.2. Initializing Two-Dimensional array:


Initializing Two-dimensional array is the process of assigning values to its all contiguous locations or to
some of them with some initial values for avoiding garbage values those are already in it. It can be
directly done with the help of assignment operator.
A Two-dimensional array is initialized as follows: array declaration follows assignment operator and
a list of values that are separated by commas enclosed with in curly braces.
Ex: int a[3][4]={{12,45,54,2},{87,76,3,4},{54,64,34,23}};
Once the above array gets initialized, the values will be stored in memory. The following memory map
depicts this thing:
From this memory map, we can observe that a Two-Dimensional array’s row’s subscript value as well as
column’s subscript’s value start from 0 and end with n-1.

9.5.3. Reading and printing Two-Dimensional array:


A Two-Dimensional array’s locations can be filled with input values from keyboard with the help of scanf()
statement. Because an array consists of more than one element, we should require loop counters for
keeping track of index values for both rows and columns. The loop counters are always integer values
those begin with 0 and ends with n-1. The loop counters should be incremented by 1 for keeping track of
next immediate indexes. For each indexed element, scanf() statement expects an input value from
programmer. This process can be depicted with the help of the following statement:
for(i=0;i<m;i++) // m: No.of rows i: loop counter for rows
for(j=0;j<n;j++) // n: No.of columns j: loop counter for columns
scanf(“%d”,&a[i][j]);
The above statement first reads a[0][0], then a[0][1], a[0][2], a[0][3]…and so on.
Once an array is read, it can be accessed directly or sequentially with the help of printf()
statement. If we want an element at particular position, then we should give the following argument to
printf() : a[row-1][column-1]. E.g., we want the element at 3 rd row and 2nd column position, then we
should give a[2][1] to printf() statement:
printf(“Element at 3rd row and 2nd column position is %d”,a[2][1]);
We can access all the elements in the array sequentially. For this, we use printf() statement along with
two loops as follows:
printf(“\n The array elements are:”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d\t”,a[i][j]);
Ex: /* Program to read and print the contents of a two-dimensional array in the form of a
matrix*/
#include<stdio.h>
main()
{ int a[10][10],m,n,i,j;
printf(“\n Enter the matrix row and column values:”);
scanf(“%d%d”,&m,&n);
printf(“\n Enter the matrix elements:”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“\n The Given Matrix\n”);
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
}
Operations on matrices:

/*Program to add two matrices*/ /*Program to multiply two matrices*/


#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a[10][10],b[10][10],c[10][10],i,j; int a[10][10],b[10][10],c[10][10],i,j;
int m,n,p,q; int m,n,p,q;

printf(“\n Enter the first matrix order:”); printf(“\n Enter the first matrix order:”);
scanf(“%d%d”,&m,&n); scanf(“%d%d”,&m,&n);
printf(“\n Enter first matrix elements:”); printf(“\n Enter first matrix elements:”);
for(i=0;i<m;i++) for(i=0;i<m;i++)
for(j=0;j<n;j++) for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]); scanf(“%d”,&a[i][j]);

printf(“\n Enter the second matrix order:”); printf(“\n Enter the second matrix order:”);
scanf(“%d%d”,&p,&q); scanf(“%d%d”,&p,&q);
printf(“\n Enter second matrix elements:”); printf(“\n Enter second matrix elements:”);
for(i=0;i<p;i++) for(i=0;i<p;i++)
for(j=0;j<q;j++) for(j=0;j<q;j++)
scanf(“%d”,&b[i][j]); scanf(“%d”,&b[i][j]);

if(m==p&&n==q) if(n==p)
{ {
for(i=0;i<m;i++) for(i=0;i<m;i++)
for(j=0;j<n;j++) {
c[i][j]=a[i][j]+b[i][j]; for(j=0;j<q;j++)
c[i][j]=0;
printf(“\n The resultant matrix \n”); for(k=0;k<n;k++)
for(i=0;i<m;i++) c[i][j]=c[i][j]+a[i][k]*b[k][j];
{ }
for(j=0;j<n;j++) printf(“\n The resultant matrix \n”);
printf(“%d\t”,c[i][j]); for(i=0;i<m;i++)
printf(“\n”); {
} for(j=0;j<n;j++)
} printf(“%d\t”,c[i][j]);
else printf(“\n”);
printf(“\n Matrix addition is not possible”); }
} }
else
printf(“\n Matrix multiplication is not
possible”);
}
/*Program to find transpose of matrix */ /*Program to compare two matrices*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a[10][10],b[10][10],i,j,m,n; int a[10][10],b[10][10],i,j;
int m,n,p,q,flag;
printf(“\n Enter the matrix order:”);
scanf(“%d%d”,&m,&n); printf(“\n Enter the first matrix order:”);
printf(“\n Enter matrix elements:”); scanf(“%d%d”,&m,&n);
for(i=0;i<m;i++) printf(“\n Enter first matrix elements:”);
for(j=0;j<n;j++) for(i=0;i<m;i++)
scanf(“%d”,&a[i][j]); for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
for(i=0;i<n;i++)
for(j=0;j<m;j++) printf(“\n Enter the second matrix order:”);
b[i][j]=a[j][i]; scanf(“%d%d”,&p,&q);
printf(“\n Enter second matrix elements:”);
printf(“\n The Transpose of matrix A \n”); for(i=0;i<p;i++)
for(i=0;i<n;i++) for(j=0;j<q;j++)
{ scanf(“%d”,&b[i][j]);
for(j=0;j<m;j++)
printf(“%d\t”,b[j][i]); if(m==p && n==q)
printf(“\n”); {
} flag=0;
}
for(i=0;i<m;i++)
/*Program to print identity matrix*/ {
#include<stdio.h> for(j=0;j<n;j++)
main() {
{ if(a[i][j]!=b[i][j])
int a[10][10],m,n,i,j; {
printf(“\n Enter matrix order:”); flag=1;
scanf(“%d%d”,&m,&n); break;
if(m!=n) }
printf(“\n Identity matrix should be }
square matrix”); }
else
{ if(flag==1)
printf(“\n Matrices are not equal”);
for(i=0;i<m;i++) else
for(j=0;j<n;j++) printf(“\n Matrices are equal”);
if(i==j) }
a[i][j]=0; else
else printf(“\n Matrix comparison is not possible”);
a[i][j]=1; }

printf(“\n Identity matrix\n”);


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
}
}
/*Program to find the trace of a matrix*/ /*Program to find the norm of a matrix*/
/*trace of matrix is sum of diagonal /*norm of matrix=square root of the sum
elements*/ of the squares of the elements of the
#include<stdio.h> matrix*/
main() #include<stdio.h>
{ #include<math.h>
int a[10][10],i,j,m,n,sum; main()
printf(“\n Enter the matrix order:”); {
scanf(“%d%d”,&m,&n); int a[10][10],i,j,m,n;
if(m!=n) long int sum;
printf(“\n Rectangular matrices don’t have double norm;
diagonal”); printf(“\n Enter the matrix order:”);
else scanf(“%d%d”,&m,&n);
{
printf(“\n Enter matrix elements:”); printf(“\n Enter matrix elements:”);
for(i=0;i<m;i++) for(i=0;i<m;i++)
for(j=0;j<n;j++) for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]); scanf(“%d”,&a[i][j]);
sum=0; sum=0;
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
if(i==j) sum=sum+a[i][j]*a[i][j];
sum=sum+a[i][j]; }
} norm=sqrt(sum);
printf(“\n Trace of matrix=%d”,sum); printf(“\n Norm of matrix=%lf”,norm);
} }
}
/*Program to check whether given
matrix is symmetric or not */
/*A is symmetric if AT=A*/
#include<stdio.h>
main()
{
int a[10][10],b[10][10],i,j,m,n,flag;
printf(“\n Enter the matrix order:”);
scanf(“%d%d”,&m,&n);
printf(“\n Enter matrix elements:”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
b[i][j]=a[j][i];
flag=0;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(a[i][j]!=b[i][j]){
flag=1;
break;
}
}
}
if(flag)
printf(“\n Given matrix is not symmetric”);
else
printf(“\n Given matrix is symmetric”);}
9.6. Passing an array as an argument
Like the values of simple variables, it is also possible to pass an array to a function. While passing
array as an argument, all the elements of array are not being passed. Instead, the name of the array is
being passed. In C, the name of an array is the primary expression whose value is the address of the first
element in the array. Hence, the arrays are passed to a function using call by reference only. By using this
method, there is no need of copying all the elements for further use in called function. Instead, the called
function refers to the array back in the calling function so that a lot of memory and time will be saved.
9.6.1. Passing one-dimensional array:
To pass a one-dimensional array to a called function, these rules should be followed:
 The function must be called by passing only the name of the array, without the subscript.
 In the function definition, the formal parameter must be an array type; the size of the array does
not need to be specified.
 The function prototype must show that the argument is an array.
The following program demonstrates passing one-dimensional array as an argument:
/*Program to find largest element in an array*/
#include<stdio.h>
int largest(int[],int); //function prototype
main()
{
int a[10[,n,big,i;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
big=largest(a,n); //function call
printf(“\n Biggest number=%d”,big);
}
int largest(int a[],int n)
{
int x;
x=a[0];
for(i=0;i<n;i++)
{
if(x<a[i])
x=a[i];
}
return x;
}

9.6.2. Passing two-dimensional array:


To pass a two-dimensional array to called function, these rules should be followed:
 The function must be called by passing only the array name.
 In the function definition, we must indicate that the array has two dimensions by including two sets
of brackets.
 The size of second dimension must be specified.
 The function prototypes should be similar to the function header.
The following program demonstrates passing two-dimensional array as an argument:
/*program to print lower triangle of a matrix*/
#include<stdio.h>
void lowertriangle(int [ ][5],int,int); //function prototype
main()
{
int a[10][5],m,n,i,j;
printf(“\n Enter the matrix order (row and column values):”);
scanf(“%d%d”,&m,&n);
printf(“\n Enter the matrix elements:”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
lowetriangle(a,m,n);
}
void lowertriangle(int a[ ][5], int m,int n)
{
int i,j;
if(m==n)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i<=j)
printf(“%d\t”,a[i][j]);
}
printf(“\n”);

}
}
else
printf(“\n Lower triangle matrix will be formed only for square matrices”);
}

9.7. Conclusion
An array is a finite, homogenous collection of elements stored in contiguous locations in memory that are
referred by a common name. An array is needed when we want a variable to store multiple values at a
time. An array is also called as an Abstract Data Type. As an ADT, array is a collection of data elements
and operations on those data items such as traversal, insertion, deletion, reversal, searching, sorting and
merging. Because an array contains at least one subscript preceded by a name, it is also called as a
subscripted variable.

You might also like