Arrays I
Arrays I
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.
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.
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.
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.
10 9 12 76 45
10 9 12 76 45
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
10 9 89 12 76 45
10 9 12 76 45
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
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
Let the element to be searched be 87. Then, Linear search works as follows:
87
87
87
87
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.
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);
}
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:
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:
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.
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; }
}
}
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.