0% found this document useful (0 votes)
4 views26 pages

Array Notes

The document provides a comprehensive overview of arrays in C programming, including their definition, declaration, initialization, and memory mapping. It covers various operations on arrays such as finding averages, largest elements, and deleting specified integers, along with example programs to illustrate these concepts. Additionally, it discusses the importance of bounds checking and the behavior of arrays in terms of memory management and initialization rules.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views26 pages

Array Notes

The document provides a comprehensive overview of arrays in C programming, including their definition, declaration, initialization, and memory mapping. It covers various operations on arrays such as finding averages, largest elements, and deleting specified integers, along with example programs to illustrate these concepts. Additionally, it discusses the importance of bounds checking and the behavior of arrays in terms of memory management and initialization rules.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

ARRAYS

Definition:

Array is an ordered collection of elements that share the same name. We use declarations to tell the compiler
when we want an array. The compiler needs to know the same things about an array that it needs to know about
an ordinary variable (known as a scalar variable in the trade): the type and the storage class. In addition, it
needs to know how many elements the array has. Arrays can have the same types and storage classes as
ordinary variables, and the same default rules apply.

Declaration of arrays:

Ex: int marks[30];


int data type of an array
marks name of an array.

The number 30 tells how many elements of type int will be in the array. This number is often called the
dimension of the array. The brackets tells compiler that we are dealing with arrays.

The dimension used to declare an array must always be a positive integer constant or an expression that can be
evaluated to be a constant, when the program is compiled.

The method of subscribing arrays is C is different from that used in many other programming languages. The
first element in the array is numbered zero so the last element is 1 less than the size of the array. However big
the array, its elements are always stored in contiguous memory locations.

The first element in the array is numbered 0. The reason for this unusual numbering scheme is that C was
designed to model the operation of computer at lower level than that dealt with by most programming
languages. The calculation of the address corresponding to subscript is simpler, when first array element is
numbered zero.

Memory map of an array:

Let us you have an array declaration as follows:

int num[5];

Since we know that array elements are stored in one continuous memory location. This is how the memory map
looks like:
num[0]

num[1]

num[2]

num[3]

num[4]

Example: To find the average marks obtained by class of 30 students in a test.

main() {
floatavg,sum=0;
int marks[30],i;
for(i=1;i<=29;i++){
printf(“Enter the marks”);
scanf(“%d”, &marks[I]);
}
for(i=0;i<=29;i++)
sum+=marks[i];
avg=sum/30;
printf(“Average is %f”,avg);
}

Initializing of an array:

A global variable is one that is declared outside any function (usually before main). A special feature of global
array is that they can be initialized when they are declared. This is done by following an array name with
dimension and equal sign, followed by pair of braces. These braces contain series of constant values, separated
by commas.

Ex: int name[5]={1,2,3,4,5};

The memory map will look like:

101 1 num[0]

103 2 num[1]

105
3 num[2]

107 4 num[3]

109 num[4]
5
It is not always necessary to specify dimension of the array, if it is being declared as follows:

int name[]={1,2,3,4,5};

Since the square brackets following the array name are empty, compiler determines how many elements to
allocate for array by counting number of values within curly braces.This approach can avoid errors.

NOTE: Defining the size of each array as a symbolic constant makes programs more scalable.

The C language treats character strings simply as array of characters.

Ex: char name[10]

Name  character array, which holds maximum of 10 characters.

When the compiler sees a constant string it terminates it with an additional null character – called as NULL
character.

Static : we have seen how global arrays can be initialized. The global variables are classified in C as static
variables, means they come into existence when program is executed, to continue to exist until entire program
terminates.

Ex: static int num;

This is to declare a local variable num as static.

In array: static int num[10];

PROGRAM: To print the sum of elements of an array.

#include<stdio.h>
intmain(){
intarr[5], i, s =0;
for(i =0; i <5; i++){
printf("Enter a[%d]: ", i);
scanf("%d",&arr[i]);
}
for(i =0; i <5; i++){
s +=arr[i];
}
printf("\nSum of elements = %d ", s);
// signal to operating system program ran fine
return0;
}

Expected Output:

Enter a[0]: 22
Enter a[1]: 33
Enter a[2]: 56
Enter a[3]: 73
Enter a[4]: 23

Sum of elements = 207


How it works?

The first for loop asks the user to enter five elements into the array. The second for loop reads all the elements
of an array one by one and in the process, accumulate the sum of all the elements of an array in the variable s.
Note that the variable s is initialized to 0, otherwise, we will get the wrong answer because of the garbage value
of s.

PROGRAM: Display Largest Element of an array

#include<stdio.h>

int main(){
int i, n;
floatarr[100];
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&n);
printf("\n");

// Stores number entered by the user


for(i =0; i < n;++i){
printf("Enter Number %d: ", i+1);
scanf("%f",&arr[i]);
}

// Loop to store largest number to arr[0]


for(i =1; i < n;++i){
// Change <to> if you want to find the smallest element
if(arr[0]<arr[i])
arr[0]=arr[i];
}
printf("Largest element = %.2f",arr[0]);
return0;
}

OUTPUT:

Enter total number of elements(1 to 100): 8

Enter Number 1: 23.4


Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5

Largest element = 55.5

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark[3] = 9;

// take input from the user and insert in third element


scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element


scanf("%d", &mark[i]);

// print first element of an array


printf("%d", mark[0]);

// print ith element of an array


printf("%d", mark[i-1]);

PROGRAM: Find the second largest & smallest elements in an array.

#include <stdio.h>
void main () {
int number[30];
int i, j, a, n, counter, average;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i){
for (j = i + 1; j < n; ++j) {
if (number[i] < number[j]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in descending order are given below \n");
for (i = 0; i < n; ++i) {
printf("%d\n", number[i]);
}
printf("The 2nd largest number is = %d\n", number[1]);
printf("The 2nd smallest number is = %d\n", number[n - 2]);
average = (number[1] + number[n - 2]) / 2;
counter = 0;
for (i = 0; i < n; ++i){
if (average == number[i]){
++counter;
}
}

if (counter == 0 )
printf("The average of %d and %d is = %d is not in the array \n", number[1], number[n - 2], average);
else
printf("The average of %d and %d in array is %d in numbers \n",number[1], number[n - 2], counter);
}

OUTPUT:
Enter the value of N
4
Enter the numbers
450
340
120
670
The numbers arranged in descending order are given below
670
450
340
120
The 2nd largest number is = 450
The 2nd smallest number is = 340
The average of 450 and 340 is = 395 is not in the array

PROGRAM: Delete the specified integer from an array.

#include <stdio.h>
void main(){
intvectorx[10];
int i, n,pos, element, found =0;
printf("Enter how many elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i =0; i < n; i++){
scanf("%d",&vectorx[i]);
}
printf("Input array elements are\n");
for(i =0; i < n; i++){
printf("%d\n",vectorx[i]);
}
printf("Enter the element to be deleted\n");
scanf("%d",&element);
for(i =0; i < n; i++){
if(vectorx[i]== element){
found=1;
pos= i;
break;
}
}
if(found ==1){
for(i =pos; i < n -1; i++){
vectorx[i]=vectorx[i +1];
}
printf("The resultant vector is \n");
for(i =0; i < n -1; i++){
printf("%d\n",vectorx[i]);
}
}
else
printf("Element %d is not found in the vector\n", element);
}

OUTPUT:
Enter how many elements
4
Enter the elements
345
234
678
987
Input array elements are
345
234
678
987
Enter the element to be deleted
234
The resultant vector is
345
678
987

PROGRAM: To count total number of array elements in C

#include <stdio.h>
int main(){
intarr[]={10,20,30,40,50};
int n;
n=sizeof(arr)/sizeof(int);
printf("Number of elemenets are: %d\n",n);
return 0;
}

OUTPUT

Number of elemenets are: 5

Another method

We can divide the occupied size of all array elements by size of any one array element. Consider the following
statement:

n=sizeof(arr)/sizeof(arr[0]);

PROGRAM: To reverse elements of an array

#include <stdio.h>
#define MAX 100

int main(){
intarr[MAX],revArr[MAX];
inti,j
int n;
printf("Enter total number of elements: ");
scanf("%d",&n);
printf("Enter array elements:\n");
for(i=0;i<n;i++){
printf("Enter element %d: ",i+1);
scanf("%d",&arr[i]);
}
for(i=(n-1),j=0; i>=0; i--,j++){
revArr[j]=arr[i];
}
printf("\nArray elements after reverse:\n");
for(i=0;i<n;i++){
printf("%d\n",revArr[i]);
}
return 0;
}

Here, in this loop:


1) There are two loop counters i and j, they are initialised with (n-1) and 0 respectively.
2) Assigning elements from last positions of first array (arr) using arr[i] to the starting of second array
(revArr) using revArr[j].
3) Since, iis initialised by (n-1) which is pointing to the last element of the first array and j is initialised by
0 which will point first element/memory block of the second array. And, iis decreasing by 1, j is
increasing by 1.
4) By using this logic - second array will be filled by the elements of first array in reverse order.

OUTPUT:
Enter total number of elements: 5
Enter array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50

Array elements after reverse:


50
40
30
20
10

Initialization and Storage Classes

We have a convenient way to initialize the array at the beginning of a program. There is a way, but only static
and extern array can be initialized but automatic and register array cannot be initialized

Before trying to initialize an array, let’s see what in it if we don’t put anything there.

main(){
int fun[2]; /*automatic array */
static int win[2]; /*static array */
printf(“%d %d\n”, fun[1], win[1]);
}

The output of this program is

This reflects the following rules. If you do noting, external and static arrays are initialized to zero. Automatic
and register arrays get whatever garbage happens to be left over in the part of memory.

When the array elements are initialized by at least one initializer, then the remaining elements are initialized to
zero.
During compile time static array gets initialized and at run time automatic array gets initialized.

Ex : main() {
int days[12] = {31,28,31,30,31,30,31,31,30,31};
int i;
for(i=0;i<12;i++)
printf(“days[%d] = %d“ , i, days[i] “);
}

The output of then following program is

days[0] = 31
days[1] = 28
days[2] = 31
days[3] = 30
days[4] = 31
days[5] = 30
days[6] = 31
days[7] = 31
days[8] = 30
days[9] = 31
days[10] = 0
days[11] = 0

Bounds checking:

In C there is no check to see if subscript used for an array exceeds size of the array. Data entered with subscript
exceeding array size will simply be placed in memory outside array: probably on top of other data. This will
lead to unpredictable results, to say the least & there will be no error message to warn you that you are going
beyond array size. In some cases, the computer may just hang. The following program my turn suicidal.

main() {
intnum[40],i;
for(i=0;i<100;i++)
num[i]=i;
}

So do remember to see to it that a subscript does not reach beyond array size is entirely the programmers
botheration & not the compilers.

Interestingly though, C is the only language which lets you exceed the limit defined in an array. Other
languages would not even allow you to trespass that boundary, acting as caretakers and dictating your
movements. C, on the other hand, acknowledges your acumen, and assuming you are aware and ready to take
the risks associated, gives you that freedom.

This situation with array bounds is one of the most unsatisfactory aspects of C. If you read or write outside of
an array's bounds, you may read or write garbage or (if you are lucky) you may get a segmentation fault which
at least tells you there's a problem.
In the end, it is up to you to make sure that your program respects the bounds of its arrays. You'll get very little
help from C.

When looping through an array, the array subscript should never go below 0 and should always
be less than the total number of elements in the array (size-1). Make sure the loop terminating
condition prevents accessing elements outside this range.
The effects of referencing elements outside the array bounds are system dependent.

Example: find the validity of the following code :

main() {
static int a[5]={5,10,15,20,25);
inti,j,m,n;
i=++a[1];
j=a[1]++;
printf(“\n i = %d j = %d a[1]=%d”,i,j,a[1]);
i=1;
m=a[i++];
printf(“\n i = %d m = %d”,i,m);
i=2;
n=a[++i];
printf(“\n i = %d n = %d”,i,n);
}

Output:

i = 11 j = 11 a[1]=12
i = 2 m = 12
i = 3 n = 20

Example: find the validity of the following code:

main() {
int list[10]={0};
int i;
for(i=0;i<5;i++)
list[2*i+1]=i+2;
for(i=0;i<10;i++)
printf(“\n %d”,list[i]);
}

Sol : 0 2 0 3 0 4 0 5 0 6

Example: find the validity of the following code:

main() {
int list[10]={2,1,2,1,1,2,3,2,1,2};
printf(“\n %d”,list[2]);
printf(“\n %d”,list[list[2]]);
printf(“\n %d”,list[list[2]+list[3]]);
printf(“\n %d”,list[list[list[2]]]);
}

Sol : 2 2 1 2
Example: find the validity of the following code:

Assume array starts at 101

main() {
int n[3][3]={1,2,3,4,5,6,7,8,9};
printf(“\n %d”,n);
printf(“\n %d”,n[2]);
printf(“\n %d ”,n[2][2]);
}

Sol: 101 113 9

Advantages of arrays

1) It is better and convenient way of storing the data of same datatype with same size.
2) It allows us to store known number of elements in it.
3) It allocates memory in contiguous memory locations for its elements. It does not allocate any extra
space/ memory for its elements. Hence there is no memory overflow or shortage of memory in arrays.
4) Iterating the arrays using their index is faster compared to any other methods like linked list etc.
5) It allows to store the elements in any dimensional array - supports multidimensional array.

Disadvantages of arrays

1) It allows us to enter only fixed number of elements into it. We cannot alter the size of the array once
array is declared. Hence if we need to insert more number of records than declared then it is not
possible. We should know array size at the compile time itself.
2) Inserting and deleting the records from the array would be costly since we add / delete the elements
from the array, we need to manage memory space too.
3) It does not verify the indexes while compiling the array. In case there is any indexes pointed which is
more than the dimension specified, then we will get run time errors rather than identifying them at
compile time.

Application to sorting:

The concept of an ordered set of elements is one that has considerable impact on our daily lives. There are
different methods of sorting. The programmer must be aware of several interrelated and often conflicting
efficiency considerations to make an intelligent choice about which sorting method is most appropriate to a
particular problem.

Here we are going to deal with two such type of sorting:

Bubble sort: The most widely known among beginning students of programming – BUBBLE SORT. One of
the main characteristic of this sort is that it is easy to understand and code.

A general algorithm for bubble sort is as follows :

1) [ Initialise ]
LAST  N ( entire list unsorted at this point )

2) [ Loop on pass index ]


Repeat thru step 5 for PASS = 1, 2, … N-1

3) [ Initialise exchanges counter for this pass ]


EXCHS  0

4) [ Perform pair wise comparisons on unsorted elements ]


Repeat for I = 1, 2, … LAST – 1
If K[I] > K[I+1]
Then K[I] -> K[I+1]
EXCHS  EXCHS + 1

5) [ Were any exchanges made on this pass ]


If EXCHS=0
Then
Return ( mission accomplished; return early)
else LAST  LAST – 1 ( reduce size of unsorted list )

6) [ Finished ]

Ex : The following elements are stored in an array :

25 57 48 37 12 92 86 33

The following comparisons are made during first pass :

x[0] with x[1] i.e 25 & 57 no interchange


x[1] with x[2] i.e 57 & 48 interchange
x[2] with x[3] i.e 57 & 37 interchange
x[3] with x[4] i.e 57 & 12 interchange
x[4] with x[5] i.e 57 & 92 no interchange
x[5] with x[6] i.e 92 & 86 interchange
x[6] with x[7] i.e 92 & 33 interchange

Thus after the first pass, array elements are like this :

25 48 37 12 57 86 33 92

Notice that after first pass, largest element 92 is in its proper position. This method is called BUBBLE SORT,
because each number slowly BUBBLES up to its position.

After second pass, the array elements will be :

25 37 12 48 57 33 86 92

The complete set of iterations is shown below :

Iteration 1 25 48 37 12 57 88 33 92
Iteration 2 25 37 12 48 57 33 86 92
Iteration 3 25 12 37 48 33 57 86 92
Iteration 4 12 25 37 33 48 57 86 92
Iteration 5 12 25 33 37 48 57 86 92
Iteration 6 12 25 33 37 48 57 86 92
Iteration 7 12 25 33 37 48 57 86 92

Hence the array elements in final stage ( after sorting ) is as follows :

12 25 33 37 48 57 86 92
PROGRAM: TO sort elements of an array using BUBBLE SORT

#include<stdio.h>
int main(){
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("\nArray after sorting: ");
for(i=0;i<n;++i)
printf("%d ",a[i]);
return 0;
}

OUTPUT:
Enter the size of array: 5
Enter the array elements: 8 4 9 6 3
Array after sorting: 3 4 6 8 9

OUTPUT:
Enter the size of array: 7
Enter the array elements: 23 12 45 78 43 89 31
Array after sorting: 12 23 31 43 45 78 89

Selection sort:

One of the easiest ways to sort a table is by selection. Suppose we have an array A with N elements A[1], A[2].
... A[N] is in memory. The selection sort algorithm for sorting works as follows :

First, find the smallest element in the list and put it in first position. Then find second smallest in list and put it
in second position. And so on.

More precisely:

Pass I : Find location LOC of smallest in list of N elements. A[1], A[2] … A[N] Then interchange A[LOC] and
A[1]. Thus A[1] is sorted.

Pass II : Find location LOC of smallest in sublist of N-1 elements. A[2], A[3] … A[N] Then interchange
A[LOC] and A[2]. Thus A[1] and A[2] is sorted. Since A[1] <= A[2].

Pass N-1 : Find location LOC of smaller of elements A[N-1], A[N] Then interchange A[LOC] and A[N-1].
Thus A[1], A[2] … A[N] is sorted. Since A[N-1] <= A[N].

Thus array is sorted after N-1 passes


Ex : Suppose an array A contains the following eight elements :

77 33 44 11 88 22 66 55

Applying selection sort algorithm to array A yields the data as given in table :

K LOC A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]


1 4 77 33 44 11 88 22 66 55
2 6 11 33 44 77 88 22 66 55
3 6 11 22 44 77 88 33 66 55
4 6 11 22 33 77 88 44 66 55
5 8 11 22 33 44 88 77 66 55
6 7 11 22 33 44 55 77 66 88
7 7 11 22 33 44 55 66 77 88

PROGRAM: TO sort elements of an array using SELECTION SORT

voidmain(){
inta[100],n,i,j,min,temp;
clrscr();
printf("\n Enter the Number of Elements: ");
scanf("%d",&n);
printf("\n Enter %d Elements: ",n);
for(i=0;i<n;i++) {
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++){
min=i;
for(j=i+1;j<n;j++){
if(a[min]>a[j])
min=j;
}
if(min!=i){
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
printf("\n The Sorted array in ascending order: ");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
getch();
}

OUTPUT:
Enter the size of array: 5
Enter the array elements: 8 4 9 6 3
Array after sorting: 3 4 6 8 9

OUTPUT:
Enter the size of array: 7
Enter the array elements: 23 12 45 78 43 89 31
Array after sorting: 12 23 31 43 45 78 89
Application to searching:

Searching refers to operation of finding the location LOC of ITEM in DATA. The search is said to be
successful if ITEM does appear in DATA and unsuccessful otherwise.

Binary search:

Suppose DATA is an array which is sorted in increasing numerical order or equivalently or alphabetically.
Then there is an extremely efficient searching algorithm called binary search which can be used to find the
location LOC of given ITEM of information in DATA.

Algorithm: The notations used are :

DATA  sorted array


LB  lower bound
UB  upper bound
ITEM  given item of information.
BEG  beginning of the segment
END  end of segment
MID  middle location of segment

The algorithm goes like this :

1) Initialize segment variables :

Set BEG := LB
END := UB
MID = INT((BEG+END)/2)

2) Repeat steps 3 and 4 while BEG <= END and DATA[MID] <> ITEM

3) If ITEM <DATA[MID] then Set END := MID – 1


Else Set BEG := MID + 1

4) Set MID := INT((BEG+END)/2)

[ end of step 2 loop ]

5) if DATA[MID] = ITEM then Set LOC := MID


else Set LOC := NULL

[ end of if structure ]

6) Exit.

Ex : let DATA be the following 13 stored element array :

DATA : 11 22 30 33 40 44 55 60 66 77 80 88 99

Let us say we apply binary search to search for an ITEM=40

Initially BEG=1 and END=13


Hence MID=INT[(1+13)/2] = 7
DATA[MID]=DATA[7]=55

Since 40 < 55 END has its value changed to END=MID-1 = 7-1 = 6


Hence MID=INT[(1+6)/2] = 3
DATA[MID]=DATA[3]=30
Since 40 > 30 BEG has its value changed to BEG=MID+1 = 3+1 = 4
Hence MID=INT[(4+6)/2] = 5
DATA[MID]=DATA[5]=40

Now since DATA[MID]=ITEM we draw conclusion that ITEM is found and search is successful. We have
found the ITEM in location LOC = MID = 5

PROGRAM: TO implement Binary Search algorithm

#include <stdio.h>

int main(){
int c, first, last, middle, n, search, array[100];
printf("\n Enter number of elements:");
scanf("%d",&n);
printf("\n Enter %d integers:", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("\n Enter value to find:");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("\n Not found! %d isn't present in the list.", search);
return 0;
}

OUTPUT:

Enter number of elements: 7


Enter 7 integers: 23
34
45
56
67
78
89
Enter value to find: 45

45 found at location 3
OUTPUT:

Enter number of elements: 5


Enter 5 integers: 34
56
67
78
89
Enter value to find: 35
Not found! 35 isn't present in the list.

Advantages of Binary search:

1) Compared to linear search (checking each element in the array starting from the first), binary search is
much faster. Linear search takes, on average N/2 comparisons (where N is the number of elements in
the array), and worst case N comparisons. Binary search takes an average and worst-case log2(N)
comparisons. So for a million elements, linear search would take an average of 500,000 comparisons,
whereas binary search would take 20.
2) It’s a fairly simple algorithm, though people get it wrong all the time.
3) It’s well known and often implemented for you as a library routine.

Disadvantages of Binary search:

1) It’s more complicated than linear search, and is overkill for very small numbers of elements.
2) It works only on lists that are sorted and kept sorted. That is not always feasible, especially if elements
are constantly being added to the list.
3) It works only on element types for which there exists a less-than relationship. Some types simply
cannot be sorted (though this is rare).
4) There is a great lost of efficiency if the list does not support random-access. You need, for example, to
immediately jump to the middle of the list. If your list is a plain array, that’s great. If it’s a linked-list,
not so much. Depending on the cost of your comparison operation, the cost of traversing a non-random-
access list could dwarf the cost of the comparisons.
5) There are even faster search methods available, such as hash lookups. However a hash lookup requires
the elements to be organized in a much more complicated data structure (a hash table, not a list).

Linear search:

Also called as sequential search.Linear search is a very simple search algorithm. In this type of search, a
sequential search is made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.

PROGRAM: To implement Linear Search algorithm

#include <stdio.h>

int main(){
int array[100], search, c, n;
printf("\n Enter the number of elements in array:");
scanf("%d", &n);
printf("\n Enter %d integer(s):", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("\n Enter a number to search:");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) /* If required element is found */
{
printf("\n %d is present at location %d.", search, c+1);
break;
}
}
if (c == n)
printf("\n %d isn't present in the array.\n", search);
return 0;
}

OUTPUT:

Enter the number of elements in array: 5


Enter 5 integer(s): 23
12
45
67
31

Enter a number to search: 67


67 is present at location 4

OUTPUT:

Enter the number of elements in array: 7


Enter 5 integer(s): 78
89
96
63
36
12
21

Enter a number to search: 45


45 isn't present in the array

PROGRAM: To implement Linear Search algorithm for multiple occurences

#include <stdio.h>

int main(){
int array[100], search, c, n, count = 0;
printf("\n Enter the number of elements in array:");
scanf("%d", &n);
printf("\n Enter %d numbers", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("\n Enter the number to search");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) {
printf("\n %d is present at location %d.\n", search, c+1);
count++;
}
}
if (count == 0)
printf("\n %d isn't present in the array.\n", search);
else
printf("\n %d is present %d times in the array.\n", search, count);

return 0;
}

OUTPUT:

Enter the number of elements in array: 7


Enter 5 integer(s): 23
12
45
67
12
33
31

Enter a number to search: 12


12 is present at location 2
12 is present at location 5
12 is present 2 times in the array

Advantages of Linear Search

1) The linear search is simple - It is very easy to understand and implement;


2) It does not require the data in the array to be stored in any particular order.

Disadvantages of Linear Search

1) The linear search is inefficient - If the array being searched contains 20,000 elements, the algorithm
will have to look at all 20,000 elements in order to find a value in the last element. In an average case,
an item is just as likely to be found near the beginning of the array as near the end. Typically, for an
array of N items, the linear search will locate an item in N/2 attempts. If an array has 50,000 elements,
the linear search will make a comparison with 25,000 of them in a typical case. This is assuming that
the search item is consistently found in the array. N/2 is the average number of comparisons. The
maximum number of comparisons is always N.

Difference between Linear Search and Binary Search

LINEAR SEARCH BINARY SEARCH


1 Sorted list is not required. Sorted list is required.
2 It can be used in linked list Implementation. It cannot be used in liked list Implementation.
3 It is suitable for a list changing very It is only suitable for static lists, because any
frequently. change requires resorting of the list.
4 The average number of comparison is very The average number of comparison is relatively
high. slow.

Multidimensional array:

From flat abstract presentations let’s move to dimensional data presentation. So far we have looked at arrays
having single dimension. It is also possible for arrays to have more than single dimension, i.e..either two or
more.
Initializing a 2-D array:

static int marks[5][2]={


{1234,56}
{1212,33}
{1434,80}
{1312,78}
{1203,75},
};

it can also be written as :

static int marks[3][2]={11,21,31,41,51,61};

of course with corresponding loss in readability.

It is important to remember that while initializing an array it is necessary to mention second column(dimension)
whereas first dimension is optional.

Ex: static int arr[2][3]={12,34,23,45,56,45};


static int arr[][3]={12,34,23,45,56,45}; are perfectly acceptable.

Whereas skipping both the dimensions or skipping the row dimension is not permitted.

Ex: static int arr[][]={12,34,23,45,56,45};


static int arr[2][]={12,34,23,45,56,45}; will not work.

Memory map of 2-D array:

Suppose you have : static int marks[3][2]={11,21,31,41,51,61};

In that case the memory map will be something like this :

Col No 0 Col No 1
Row No 0 11 21
Row No 1 31 41
Row No 2 51 61

This is drawn for our reference. This arrangement is conceptually true. This is because in memory there are no
rows & columns. In memory, irrespective of dimensions the array elements are stored in one continuous chain.
The actual memory map is shown below :

101 marks[0][0] 11
103 marks[0][1] 21
105 marks[1][0] 31
107 marks[1][1] 41
109 marks[2][0] 51
111 marks[2][1] 61
PROGRAM: To illustrate the concept of two dimensional array

#include<stdio.h>
int main(){
intdisp[2][3];/* 2D array declaration*/
int i, j;
for(i=0; i<2; i++){
for(j=0;j<3;j++){
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d",&disp[i][j]);
}
}

printf("Two Dimensional array elements:\n");


for(i=0; i<2; i++){
for(j=0;j<3;j++){
printf("%d ",disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return0;
}

OUTPUT:

Enter value fordisp[0][0]:1


Enter value fordisp[0][1]:2
Enter value fordisp[0][2]:3
Enter value fordisp[1][0]:4
Enter value fordisp[1][1]:5
Enter value fordisp[1][2]:6
TwoDimensional array elements:
123
456

PROGRAM: To read a matrix and prints sum and product of all elements of the two dimensional array.

#include <stdio.h>
#define MAXROW 10
#define MAXCOL 10

int main(){
int matrix[MAXROW][MAXCOL];
inti,j,r,c;
intsum,product;
printf("Enter number of Rows :");
scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);
printf("\nEnter matrix elements :\n");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
} }
sum=0; /*initializing sum and product variables*/
product=1;
for(i=0;i<r;i++){
for(j=0;j<c;j++){
sum+=matrix[i][j];
product*=matrix[i][j];
}
}
printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);
return 0;
}

OUTPUT:
Enter number of Rows :3
Enter number of Cols :3

Enter matrix elements :


Enter element [1,1] : 1
Enter element [1,2] : 1
Enter element [1,3] : 1
Enter element [2,1] : 2
Enter element [2,2] : 2
Enter element [2,3] : 2
Enter element [3,1] : 3
Enter element [3,2] : 3
Enter element [3,3] : 3

SUM of all elements : 18


Product of all elements :216

PROGRAM: To find Transpose of a matrix

void main(){
staticint array[10][10];
int i, j, m, n;
printf("Enter the order of the matrix \n");
scanf("%d %d",&m,&n);
printf("Enter the coefiicients of the matrix\n");
for(i =0; i < m;++i){
for(j =0; j < n;++j){
scanf("%d",&array[i][j]);
} }
printf("The given matrix is \n");
for(i =0; i < m;++i){
for(j =0; j < n;++j){
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for(j =0; j < n;++j){
for(i =0; i < m;++i){
printf(" %d", array[i][j]);
}
printf("\n");
}
}

OUTPUT:

Enter the order of the matrix


33
Enter the coefiicients of the matrix
379
275
634
The given matrix is
379
275
634
Transpose of matrix is
326
773
954

PROGRAM: To multiply two matrices

#include<stdio.h>

int main(){
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d %d",&r1,&c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2,&c2);

// Column of first matrix should be equal to column of second matrix and


while(c1 != r2){
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d",&r1,&c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2,&c2);
}

// Storing elements of first matrix.

printf("\nEnter elements of matrix 1:\n");


for(i=0; i<r1;++i)
for(j=0; j<c1;++j){
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d",&a[i][j]);
}

// Storing elements of second matrix.

printf("\nEnter elements of matrix 2:\n");


for(i=0; i<r2;++i)
for(j=0; j<c2;++j){
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}
// Initializing all elements of result matrix to 0

for(i=0; i<r1;++i)
for(j=0; j<c2;++j){
result[i][j]=0;
}

// Multiplying matrices a and b andstoring result in result matrix


for(i=0; i<r1;++i)
for(j=0; j<c2;++j)
for(k=0; k<c1;++k){
result[i][j]+=a[i][k]*b[k][j];
}

// Displaying the result

printf("\nOutput Matrix:\n");
for(i=0; i<r1;++i)
for(j=0; j<c2;++j){
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return0;
}

OUTPUT:
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29

6 25
PROGRAM: To find row sum and column sum of matrix

#include<stdio.h>
int main(){
int i, j, rows, columns, a[10][10], Sum;
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++){
for(columns = 0; columns < j; columns++){
scanf("%d", &a[rows][columns]);
}
}
for(rows = 0; rows < i; rows++) {
Sum = 0;
for(columns = 0;columns < j; columns++){
Sum = Sum + a[rows][columns];
}
printf("\n The Sum of Elements of a Rows in a Matrix = %d", Sum );
}

for(rows = 0; rows < i; rows++) {


Sum = 0;
for(columns = 0;columns < j; columns++){
Sum = Sum + a[columns][rows];
}
printf("\n The Sum of Elements of a Columns in a Matrix = %d", Sum );
}
return 0;
}

OUTPUT:

Please Enter Number of rows and columns: 3 3


Please Enter the Matrix Elements
10 11 12
13 14 15
16 17 18

The Sum of Elements of a Rows in a Matrix = 33


The Sum of Elements of a Rows in a Matrix = 42
The Sum of Elements of a Rows in a Matrix = 51
The Sum of Elements of a Columns in a Matrix = 39
The Sum of Elements of a Columns in a Matrix = 42
The Sum of Elements of a Columns in a Matrix = 45

OUTPUT:

Please Enter Number of rows and columns: 2 2


Please Enter the Matrix Elements
56
78

The Sum of Elements of a Rows in a Matrix = 11


The Sum of Elements of a Rows in a Matrix = 15
The Sum of Elements of a Columns in a Matrix = 12
The Sum of Elements of a Columns in a Matrix = 14

3-D arrays: Very rarely used.


Ex: static int arr[2][3][5]={
{
{2,4,5,6,4},
{7,8,9,0,2},
{3,4,5,6,7},
},
{
{2,2,3,4,5},
{2,3,2,3,7},
{3,4,5,1,9},
}
};

3-D array can be thought of array of array of array. The outer array has two elements, each of which is one
dimensional array of 5 elements.

How will we represent element 1 in above matrix as an array:

The first subscript should be [1], since element is in second 2-D array, the second subscript is [2], since element
is in third row of 2-D array. The third subscript should be [3] since elements is in fourth position of one
dimensional array.

i.e, arr[1][2][3];

You might also like