You are on page 1of 27

11

Arrays- I
(Numeric Arrays)

In this chapter, you will learn:

 What is an array?
 Types of arrays: one-dimensional, multi-dimensional
arrays
 One-dimensional array: Declaration, initialization and
reading and printing
 Operations on 1-D array: Traversing,Insertion,
deletion, searching, sorting and merging
 Two-dimensional array: Declaration, initialization and
reading and printing
 Operations on matrices: addition, multiplication,
transpose and equality
 Arrays as arguments to a function
What is an array?
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 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.

2
Types of Arrays
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.

One-dimensional array
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:
<data type> <array_name>[size];
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.
Size is any non-negative integer constant or integer expression.
Ex: 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.
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

12 45 55 4 99 3 67
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., 4 th element of
array ‘a’ is identified with a[3] or 1000+(4-1)*2=1006.

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]);
Ex: /* Program to read and print the contents of a one-dimensional array*/
#include<stdio.h>
main()
{
int a[10],n,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]);

printf(“\n The array elements:”);


for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}

4
Examples:
/*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]);
}

5
Operations on arrays

An array is a derived data type. A derived data type is a collection of data and operations on
that data. As a derived data type, 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.
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.

Traversing:
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:
#include<stdio.h>
main()
{
int a[10],n,LB,UB;
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
LB=0;
UB=n-1;
for(i=LB;i<UB;i++)
scanf(“%d”,&a[i]);
for(i=LB;i<UB;i++)
printf(“%d\t”,a[i]);
}

Insertion:
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]


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

Deletion:
Deletion is the process of removing an existing element from an array. This deletion 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]

7
Suppose, we want to delete an element at third 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 by 1. Hence, the length of array now becomes 4. Now, the new 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,i,pos;
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 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; //step 3
printf(“\n New array:”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}

Searching: It is the process of finding the location of an element in the given array of
elements. There are 3 methods for achieving this searching process:
1) Linear Search (or) Sequential search
2) Binary Search
3) Fibonacci Search

Linear Search: This method works on this principle: “Compare each element of the array
with the element that is to be searched. If the suitable match is found, then return the position
by leaving the later comparisons; otherwise, leave the proper message to the programmer
after the end of the array gets reached “.

8
This method best can be explained with the following example:
Suppose, there is an array that has 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]

9
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.
10
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.

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

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

Sorting: Let A be a 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:

 Selection sort
 Bubble sort
 Insertion sort

Selection sort: Suppose an array A with n elements A[0], A[1], A[2] … A[n-1] is in memory.
Then in selection sort, first find the smallest element in the list and put it in the first position.
Then find the second smallest element in the list and put it in second position… and so on.

The selection sort method is carried out like this:

13
Pass 1: Find the location LOC of the smallest element in the list of n elements:
A[0],A[1],A[2]…A[n-1]. After then, interchange A[LOC] and A[0]. Now, observe
that A[0] is sorted.
Pass 2: Find the location LOC 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[LOC] and A[1]. Now, observe
that A[0] and A[1] are sorted, since A[1]<=A[0].
Pass 3: Find the location LOC 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[LOC] and A[1]. Now, observe
that A[0] and A[1] are sorted, since A[1]<=A[0].
…….
…….
Pass n-1: Find the location LOC of the smaller of the elements A[n-2] and A[n-1]. After then,
interchange A[LOC] 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].
Example: suppose an array A contains 8 elements as follows:

77 33 44 11 88 22 66 55

14
The following program demonstrates the selection sort technique:
/*Selection sort*/
#include<stdio.h>
main()
{
int a[10],n,k,LOC,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(k=0;k<n-1;k++)
{
LOC=k;
for(j=k+1;j<n;j++)
if(a[LOC]>a[j])
LOC=j;
if(LOC!=k)
{
temp=a[k];
a[k]=a[LOC];
a[LOC]=temp;
}
}
printf(“\n Sorted list (Selection sort):”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}

Insertion sort: Suppose an array A with n elements A[0], A[1], A[2] … A[n-1] is in memory.
Then 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[k-1].
The insertion sort 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-1] with A[k-2], A[k-2] with A[k-3]… and so
on until first meeting an element A[j] such that A[j]<=A[k]. Then each of the elements A[k-1],
A[k-2]… A[j+1] is moved forward to one location and A[k] is inserted in j+1 st position.

15
Example: suppose an array A contains 8 elements as follows:

77 33 44 11 88 22 66 55

The following program demonstrates the insertion sort technique:


/*Insertion sort*/
#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-1;
while(temp<a[j])
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
printf(“\n Sorted list (Insertion sort):”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}

16
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 process:

17
The following code demonstrates bubble sort:
/*Bubble sort*/
#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=n-1;i>=0;i--){
for (j = 1; j <= i; j++){
if (a[j-1] > a[j]){
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
printf(“\n Sorted list (Bubble sort):”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}

18
Merging: It is the process of combining two sorted arrays into one sorted array. Suppose that
there are two sorted arrays A and B having elements n and m elements respectively. These
are merged to give sorted array C of size lesser than n+m if there are duplicate elements in
the arrays A and B.

The following program demonstrates this merging:


/*Merging two sorted arrays*/
#include<stdio.h>
main()
{
int a[10],n,b[10],m,c[20],i,j,k,l;

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


scanf(“%d”,&n);
printf(“\n Enter array elements in sorted order:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);

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


scanf(“%d”,&n);
printf(“\n Enter array elements in sorted order:”);
for(i=0;i<m;i++)
scanf(“%d”,&b[i]);

19
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=i;l<n;l++)
{
c[k]=a[l];
k++;
}
}

if(j<m)
{
for(l=j;l<m;l++)
{
c[k]=b[l];
k++;
}

}
printf(“\n Merged List of elements:”);
for(i=0;i<k;i++)
printf(“%d\t”,c[i]);
}

20
Two-Dimensional array
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.

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

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:

21

12 45 55 4 99 3 67
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.
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”);
}
}

22
/*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”);
}

23
/*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”);
}
}
}

24
/*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”);}

25
Passing array as an argument to a function
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.
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;
}

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.

26
 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”);
}

27

You might also like