You are on page 1of 44

UNIT- I ARRAYS AND STRINGS

Arrays
Definition:

An array is a collection of same data items, that are stored under a common name.
A value in an array is identified by index or subscript enclosed in square brackets
[ ]with array name.
The individual data items can be integer, float, and characters and so on, but they must
be the same type and same storage class.
Thus ‘n’ elements are ‘A’ and the elements are

A[0], A[1],A[2],A[3],………………..A[n-1]

Example:

int A[5];

Arrays can be classified into

1.One-Dimensional Array
2.Two- Dimensional Arrays
3.Multi- Dimensional Arrays

1
Features of Array

An array is a derived data type. It is used to represent a collection of elements of the


same data type.
The elements can be accessed with base address (index) and the subscripts define the
position of the element.
In array the elements are stored in continuous memory location.
It is easier to refer the array elements by simply incrementing the value of the subscript.

Advantages of Array

Less amount of code


Easy access of elements
Easy to implementation algorithm
Random access

Accessing Array Elements

Array elements can be referred with subscript ( [ ] ), the number in the brackets
following the array name.

This number specifies the element‟s position in the array.

Array element starts with value 0.

Example:

int A[5];

2
Arrays Declaration
Definition:

To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array.

Syntax:
data- type array-Name [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant


greater than zero and data_type can be any valid C data type.

Example:

int a[5]; // single-dimensional array

char name[20]; // single-dimensional array

int a[3][3]; // two-dimensional array

int a[3][3][3][3]; // multi-dimensional array

Example Program:

#include<stdio.h>
void main()
{
char name[20];
printf("Enter the name ");
scanf("% s",&name);
printf(“s”, name);
}
3
Arrays Initialization

We can initialize array in C either one by one or using a single statement as follows:

int mark[5] = {80,90,99,97,95};


80 90 99 97 95
mark[0] mark[1] mark[2] mark[3] mark[4]

int b[] = {10, 11, 12, 13, 14};


10 11 12 13 14
b[0] b[1] b[2] b[3] b[4]

char m1[6] = „H‟,‟e‟,‟l‟,‟l‟,‟o‟; H e l „\0‟ l o


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

char m2[] = "world";


w o r „\0‟l d
m2[0] m2[1] m2[2] m2[3] m2[4] m2[5]

The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ].

4
Example Program: Output

#include<stdio.h>
#include<conio.h>
void main()
{
int i, array[5]={10,20,30,40,50};
clrscr();
array[0]=10;
array[1]=20;
array[2]=30;
array[3]=40;
array[4]=40;
for(i=0;i<5;i++) value of array[1] is 10
{ value of array[2] is 20
printf("value of array[%d] is %d \n",i,array[i]); value of array[3] is 30
} value of array[4] is 40
getch(); value of array[5] is 50
}

5
One Dimensional Array

Definition:

The collection of same data item can be stored under a variable name using only one
subscript such variable is called One-Dimensional Array

Syntax:

data-type array-variable[size or subscript of the array];

Example:

int a[5];

Explanation:

‘a’ is the name of the array with 5 subscripts of integer data types and the computer
reserved five storage locations as .
a
a[0]

a[1]

a[2]

a[3]

a[4]

6
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],sum=0,i;
clrscr();
printf("Enter 5 integer numbers:");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum of given numer is :%d",sum);
getch();
}

a[0] 7

a[1] 2
Sample Output:
a[2] 8

a[3] 3

a[4] 6

The sum of given numer is : 26

7
Computing Mean, Median and Mode
Mean:
Mean is same as average.

The Mean is found by adding up all of the given data and diving by number of elements.

Example:

Mean of 1,2,3,4 and 5 is (1+2+3+4+5) / 5 = 3

Median:
Median is the middle number in an ordered list (ascending or descending order).

First the numbers must be arranged either ascending or descending order.

Example:

Median of 1, 2,3,4,5 is 3

Mode:

Mode is the element which happens most number of times in the list.
If no element happens more than once, all elements are considered as mode.

Example:

Mode of 1,2,1,3,1,4,5 is 1.

Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[20],sum=0,n,t,b[20],k=0,c=1,max=0,mode;
float x=0.0,y=0.0;
clrscr();
printf("\nEnter the limit\n");
8
scanf("%d",&n);
printf("Enter the set of numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
x=(float)sum/(float)n;
printf("Mean\t= %f",x);

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
if(n%2==0)
y=(float)(a[n/2]+a[(n-1)/2])/2;
else
y=a[(n-1)/2];
printf("\nMedian\t= %f",y);

for(i=0;i<n-1;i++)
{
mode=0;
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
mode++;
}
}
if((mode>max)&&(mode!=0))
{
k=0;
max=mode;
b[k]=a[i];
9
k++;
}
else if(mode==max)
{
b[k]=a[i];
k++;
}
}
for(i=0;i<n;i++)
{
if(a[i]==b[i])
c++;
}
if(c==n)
printf("\nThere is no mode");
else
{
printf("\nMode\t= ");
for(i=0;i<k;i++)
printf("%d ",b[i]);
}
getch();
}

Output -1 Output -2

Enter the limit Enter the limit


5 6
Enter the set of numbers Enter the set of numbers
7 7
9 9
3 3
10 10
9 4
Mean = 7.6000 2
Median = 9.000 Mean = 5.8333
Mode = 9 Median = 5.500
There is no mode

10
Two- Dimensional Arrays

Definition:

The Two- Dimensional Arrays are store in a row-column matrix, where the left index
indicates the row and the right indicates the column.

Syntax:

data-type array-name[row size][column size];

Example:
int a[2][2];

Explanation:

„a‟ is the array name and it reserves 2 rows and 2 column of memory.

column 0 column 1

row 0

row 1

a[0][0] a[0][1]

a[1][0] a[1][1]

11
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int stu[2][2],i;
clrscr();
for(i=0;i<2;i++)
{
printf("Enter roll no and mark:");
scanf("%d%d",&stu[i][0],&stu[i][1]);
}
for(i=0;i<2;i++)
printf(" roll no %d mark %d \n",stu[i][0],stu[i][1]);
getch();
}

Sample Output:

stu[0][0] stu[0][1]

1 89
roll no 1 mark 89
2 95
roll no 2 mark 95
stu[1][0] stu[1][1]

12
Matrix

A matrix is a rectangular array of numbers arranged in rows and columns.

1. Matrix Addition

Program:

#include<stdio.h>
#include<conio.h>
int a[10][10],b[10][10],c[10][10],m,n,i,j;
void main()
{
clrscr();
printf("Enter the rows and columns of two matrixes\n");
scanf("%d %d",&m,&n);
printf("Enter the elements of A matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of B matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
13
printf(" \n A Matrix");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t %d",a[i][j]);
}
}
printf("\n B Matrix");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t %d",b[i][j]);
}
}

printf("\nThe addition of 2 matrixes are:\n");


for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]); }
}
getch();
}

14
Output:
Enter the rows and columns of two matrixes
3
3
Enter the elements of A matrix
1
2
3
4
5
6
7
8
9

Enter the elements of B matrix


1
2
3
4
5
6
7
8
9

15
A Matrix
1 2 3
4 5 6
7 8 9

B Matrix
1 2 3
4 5 6
7 8 9

The addition of 2 matrixe are:

2 4 6
8 10 12
14 16 18

16
2. Matrix Multiplication

Program:

#include<stdio.h>
#include<conio.h>
int a[10][10],b[10][10],c[10][10],m,n,i,j,k;
void main()
{
clrscr();
printf("Enter the rows and columns of two matrixes\n");
scanf("%d %d",&m,&n);
printf("Enter the elements of A matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("Enter the elements of B matrix\n");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}

17
printf(" \n A Matrix");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t %d",a[i][j]);
}
}
printf("\n B Matrix");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t %d",b[i][j]);
}
}

for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=0;
for(k=0;k<m;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];

}
}
18
printf("\nThe Multiplication of 2 matrixes are:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t%d",c[i][j]);
}
}
getch();
}

19
Output:
Enter the rows and columns of two matrixes
3
3
Enter the elements of A matrix
1
2
3
4
5
6
7
8
9
Enter the elements of B matrix
1
2
3
4
5
6
7
8
9

20
A Matrix
1 2 3
5 5 6
7 8 9

B Matrix
1 2 3
5 5 6
7 8 9

The Multiplication of 2 matrixes are:

30 36 42

66 81 96

102 126 150

21
3. Transpose of Matrix

Definition:

The Transpose of a matrix is obtained by interchanging rows and columns of a matrix.


Example
1 2
3 4
5 6
then, transpose of above matrix will be
1 3 5
2 4 6
Program:

#include<stdio.h>
#include<conio.h>
int a[10][10],c[10][10],m,n,i,j;
void main()
{
clrscr();
printf("Enter the rows and columns of matrix\n");
scanf("%d %d",&m,&n);
printf("Enter the elements of matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}

22
printf("\nThe given matrix is :\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t%d",a[i][j]);
}
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[j][i]=a[i][j];
}
}

printf("\nThe transpose matrix is :\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<m;j++)
{
printf("\t%d",c[i][j]);
}
}
getch();
}

23
Output:

Enter the rows and columns of matrix


3
2
Enter the elements of matrix
1
2
3
4
5
6

The given matrix is :

1 2
3 4
5 6

The transpose matrix is :


1 3 5
2 4 6

24
4. Scalar matrix

Definition:

Scalar multiplication of matrix is defined by

(nA)ij=n.Aij

Example
1 2 3 3 6 9
3 * 4 5 6 = 12 15 18
7 8 9 21 24 27

Program:

#include<stdio.h>
#include<conio.h>
int a[10][10],c[10][10],m,n,i,j;
void main()
{
clrscr();
printf("Enter the rows and columns of matrix\n");
scanf("%d %d",&m,&n);
printf("Enter the elements of matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
25
printf("\nThe given matrix is :\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("\t%d",a[i][j]);
}
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=n*a[i][j];
}
}

printf("\nThe Scalar matrix is :\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<m;j++)
{
printf("\t%d",c[i][j]);
}
}
getch();
}

26
Output:
Enter the rows and columns of two matrixes
3
3
Enter the elements of matrix
2
3
4
5
6
7
8
9

The given matrix is :

1 2 3
4 5 6
7 8 9

The Scalar matrix is :

3 6 9

12 15 18

21 24 27

27
5. Determinant of matrix

Definition:

The Determinant of matrix is a spcial number that can be calculated from the elements
of a square matrix.
The Determinant of matrix A is denoted by det(A), det A or [A]

a b
If A= Then, A =ad-bc
c d

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3], i, j;
long determinant;
clrscr();
printf("Enter the 9 elements of matrix: ");
for(i = 0 ;i < 3;i++)
{
for(j = 0;j < 3;j++)
{
scanf("%d", &a[i][j]);
}
}

28
printf("\nThe given matrix is\n");
for(i = 0;i < 3; i++)
{
printf("\n");
for(j = 0;j < 3; j++)
printf("%d\t", a[i][j]);
}

determinant = a[0][0] * ((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1] * (a[1][0]


* a[2][2] - a[2][0] * a[1][2]) + a[0][2] * (a[1][0] * a[2][1] - a[2][0] * a[1][1]);

printf("\nDeterminant of 3X3 matrix: %ld", determinant);


getch();
}

Output:
Enter the 9 elements of matrix:
5
-2
1
0
3
-1
2
0
7

The given matrix is

5 -2 1
0 3 -1
2 0 7
Determinant of 3X3 matrix: 103
29
Multi- Dimensional Arrays

Definition:

The dimension with three or more called Multi- dimensional arrays.


Syntax:
data-type array-name[size 1][ size 2] [size 3]…… [size n];

Example:
int a[2][2][2];

Example Program:

#include<stdio.h>

#include<conio.h>

void main()

int stu[2][2][2],i,j,k;

clrscr();

printf("Enter Value");
for(i=0;i<2;i++)

{
for(j=0;j<2;j++)

for(k=0;k<2;k++)

scanf("%d",&stu[i][j][k]);
}}}

30
for(i=0;i<2;i++)
{

for(j=0;j<2;j++)

for(k=0;k<2;k++)

printf("%d",stu[i][j][k]);

printf("\t");

}}
printf("\n");

getch();

Sample Output:

stu[0][0][0] stu[0][0][1] stu[0][1][0] stu[0][1][1]

5 7 6 8

3 2 1 3

stu[1][0][0] stu[1][0][1] stu[1][1][0] stu[1][1][1]

31
Strings

Definition:

In „C‟ language the group (sequence or collection) of character, digits, and symbols
enclosed within quotation marks („ or “) are called as string.
A string variable is any „C‟ variable name and is always declared as an array
Null character (‘\0’) is used to mark the end of the string.

Syntax:
char string name[size ];

Example:

char name[ ] = {„c‟,‟o‟,‟m‟,‟e‟,‟\0‟};


char name[ ] = “come”;
char name[20 ] ;

Example Program:

#include<conio.h>
#include<stdio.h>
void main()
{
char name[20];
clrscr();
scanf("%s",&name); //Reading String
printf("%s",name); //Writing String
getch();
}

32
String operations (String handling functions)

The „C‟ compiler provides the following string handling functions:

Function Purpose

strlen() Used to find the length of the string

strcpy() Used to copy one string to another

strcat() Used to combine two strings

Used to compare characters of two strings (difference between small and


strcmp()
capital letters)

strlwr() Used to convert strings into lower case

strupr() Used to convert strings into upper case

strdup() Used to duplicate a string

strrev() Used to reverse a string

Strncpy() Used to copy first „n‟ characters of one string to another

Strncmp() Used to compare first „n‟ characters of two strings.

Strcmpi() Used to compare two strings without regarding the case.

strnicmp() Used to compare first „n‟ characters of two strings without regarding the case.

Stricmp() Compares two strings (Not difference between small and capital letters)

strchr() Determines first occurrence of a given character in a string.

strrchr() Determines last occurrence of a given character in a string.

strstr() Determines first occurrence of a given string in another string

strncat() Appends source string to destination string upto specified length.

33
Sets specified number of characters of string with a given argument or
strnset()
symbol.

strspn() Finds upto what length two strings are identical.

Searches the first occurrence of the character in a given string and then it
strpbrk()
displays the string starting from that character.

1. strlen()----String length

This function is used to find the length of the string.

Syntax:
var = strlen(string);

Example Program:

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str[10];
clrscr();
printf("\n\t Enter your name : ");
scanf("%s",&str);
printf("\nLength of String: %d",strlen(str));
getch();
}

INPUT:

Enter the string: college

OUTPUT:

Length of string is 7

34
2. strcpy( )----Copying the String

This function used to copy one string to another and it almost works like string assignment operator.
Syntax:

strcpy(string1, string2)

Description:

string1 is the destination string


string2 is the source string

Example :1 char str1[ ] = “ science”

char str2[ ] = “ engineering”

strcpy(str1, str2)

Example:2
char str1[10 ]

char str2[ ] = “ engineering”

strcpy(str1, str2)

Example Program:

#include<stdio.h> INPUT:
#include<conio.h>
#include<string.h> Enter the two strings:
void main()
{ science
char str1[20],str2[20];
clrscr();
engineering
printf("Enter the two strings: ");
scanf("%s%s",&str1,&str2);
strcpy(str1,str2);
printf("%s",str1); OUTPUT:
printf("%s",str2);
getch(); engineering
}
engineering

35
3. strcat() --String Concatenation

The strcat( ) function used to combine two strings or joins two strings together.

Syntax:

strcat(string1, string2)

Example :
char str1[10 ]

char str2[10 ]

strcat(str1, str2)

Example Program:

#include<stdio.h> INPUT:
#include<conio.h>
Enter the two strings:
#include<string.h>
void main() anna

{
university
char str1[20],str2[20];
clrscr();
OUTPUT:
printf("Entere the two strings");
scanf("%s%s",&str1,&str2); concatenated strings is
strcat(str1,str2);
Anna university
printf("concatenated strings is %s",str1);
getch();
}

36
4. strcmp() ----String Comparison

This function is used to compare two strings and returns integer value.
If both the string are equal then this function will return 0, otherwise it may return a negative or
positive value based on the comparison.

Syntax:
strcmp(string1, string2)

Example Program:

#include<stdio.h>
#include<conio.h> INPUT:
#include<string.h>
void main() Enter the two strings:
{
char str1[20],str2[20]; apple
clrscr();
printf("Entere the two strings");
orange
scanf("%s%s",&str1,&str2);
if(strcmp(str1,str2)>0)
printf(" string1 is greater");
else OUTPUT:
printf("string2 is greater");
getch(); string2 is greater
}

Example Program for strlwr( ); , strupr( ); , strrev( ); and strlen( )

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str[50];
clrscr();
printf("\n\t Enter your name : ");
gets(str);
printf("\nLower case of string: %s",strlwr(str));
printf("\nUpper case of string: %s",strupr(str));
printf("\nReverse of string: %s",strrev(str));
printf("\nLength of String: %d",strlen(str));
getch();
}
Input:
Enter your name: cse
Output:
Lower case of string: cse
Upper case of string: CSE 37
Reverse of string : ESC
Length of String :3
/*Illustration of string-handling functions*/

#include<stdio.h> OUTPUT :1
#include<conio.h> Enter two string constants
#include<string.h> New
void main() York
{ Strings are not equal
char s1[20],s2[20],s3[20]; s1 = New York
int x, m1, m2, m3; length = 7 characters
clrscr(); s2 = York
printf("Enter two string constants \n"); length = 4 characters
scanf("%s %s", &s1, &s2); s3 = New York
x = strcmp(s1, s2); length = 7 characters
if(x != 0)
{ OUTPUT:2
printf("Strings are not equal \n");
strcat(s1, s2); Enter two string constants
} London
else London
{ Strings are equal
printf("Strings are equal \n");
} s1 = London
strcpy(s3,s1); length = 6 characters
m1 = strlen(s1); s2 = London
m2 = strlen(s2); length = 6 characters
m3 = strlen(s3); s3 = London
printf("\ns1 = %s \t length = %d characters \n",s1, m1); length = 6 characters
printf("\ns2= %s \t length = %d characters \n",s2, m2);
printf("\ns3 = %s \t length = %d characters \n",s3, m3);
getch();
}

38
//’C’- Program for Palindrome string OUTPUT
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char a[100], b[100];
clrscr();
printf("Enter the string \n");
gets(a);
strcpy(b,a);
strrev(b);
if( strcmp(a,b) == 0 )
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");
getch();
}

39
Sorting

Sorting means to sort an array of data.

Ascending order sort starts from the smallest or lowest value (0,1, 2, ….. or A, B, C,…..)

Descending order sort starts with the highest and proceeds to the lowest. (9, 8, 7…. or Z, Y, X….)

There are many different types of sorting algorithms.

Selection sort
Bubble sort
Insertion sort

SELECTION SORT:

Definition:
Selection sort selects the smallest element in the list and place in the first positions.
Then, selects the second smallest element and place it in the second position and it
proceeds in the similar ways until the entire list is sorted.

Example:

40
Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,a[20],temp;
clrscr();
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter %d elements: ",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Selection Sorting:"); printf("Ascending order:");
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
printf("%d",a[i]); printf("%d",a[i]);
} }
printf("Descending order:");
for(i=n-1;i>=0;i--)
{
printf("%d",a[i]);
}
getch(); getch();
} }
Output Output
Enter total elements: 5 Enter total elements: 5
Enter 5 elements: 4 5 0 2 1 Enter 5 elements: 4 5 0 2 1
Selection Sorting: 0 1 2 4 5 Ascending order : 0 1 2 4 5
Descending order : 5 4 2 1 0

Analysis of Selection Sort


Best case Analysis = O (N)
2
Average Case Analysis = O ( N )
Worst case Analysis = O ( N2)
41
Searching
Searching is just trying to find the data (information) you need.

1. Linear search :

Definition:
Linear search or sequential search is a method for finding a particular value in a list, that consists of
checking every one of its elements, one at a time and in sequence.
Example:

Example Program Output:

#include<stdio.h> Enter the size of an array: 5


#include<conio.h>
void main() Enter the elements of the array: 4 6 8 0 3
{
Enter the number to be search: 8
int a[10],i,n,m,c=0;
clrscr(); 8 is present at location 3
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

printf("Enter the number to be search: ");


scanf("%d",&m);
for(i=0;i<n;i++)
{
if(a[i]==m)
{
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("%d is present at location %d",m , i+1);

getch();
}

42
2. Binary search :

Definition:
Binary search is also called half-interval search (or) logarithmic search (or) binary chop algorithm
It is used to finds the position of a specified input value (the search "key") within an array sorted by key
value.

Example Program Output:

#include<stdio.h> Enter the size of an array: 5


#include<conio.h>
void main() Enter the elements in ascending order: 4 7 8 11 21
{
int a[10],i,n,m,c=0,first,last,mid; Enter the number to be search: 11
clrscr();
printf("Enter the size of an array: "); 11 is present at location 4
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

printf("Enter the number to be search: ");


scanf("%d",&m);
first=0;
last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
last=mid-1;
}
else
first=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("%d is present at location %d",m,mid+1);
getch();
}

43
Example:

Analysis of Searching

Types of Searching Best case Average case Worst case

Linear Searching O ( 1) O ( N) O ( N)

Binary Searching O (1) O ( log N) O ( log N)

Difference between Linear Search and Binary Search

S.No Linear Search Binary Search

1 Every element in the data set is compared Only the middle element of the data set is
until the key value is found compared

2 The search space includes the entire data set The search space is halved, on each pass

3 The data need not be sorted It works only on sorted data

4 It is efficient than the linear search but more


It is very easy and simple
complex than it

44

You might also like