In this article linear search in c we give the information about the given element is searched sequentially i.e. the given element is compared with each element of an array until the element is found.
Linear Search in C
Introduction to searching:
Searching is an operation which finds the location of a given element in a given list of elements. The result of the searching is said to be successful if the given element is found in that list otherwise searching is said to be unsuccessful.
Linear Search Example:
Suppose the data contains 7 elements as follows
Data : 12, 89, 41, 33, 52, 09, 19
Searching for element 33
Data : 09, 12, 19, 33, 41, 52, 89
Searching is successful.
Searching for element 110
Data : 09, 12, 19, 33, 41, 52, 89
Searching is unsuccessful.
Searching Methods:
There are two methods for searching such as
- Linear Search
- Binary Search
Linear Search:
Concept:
The Linear search method is simplest method of searching. In this methods, the given element is searched sequentially i.e. the given element is compared with each element of an array until the element is found.
If the element found in an array then the search is successful other-wise, the search is unsuccessful. The linear search method is used with the unsorted data.
Linear Search Algorithm:
Step 1: Start
2: Read n element of an array arr[ ].
3: Read y as element to be search
4: Initialize i=0 and if i is less than n-1 then repeat following steps
If arr[i] = y then
Display “Given number is found i.e. Search is successful” and go to step 6. Other wise goto next step
5: Display “ Given number is not found i.e. Search is Unsuccessful ”.
6: stop.
// Linear Search Program
Int main()
{
Int arr[7]={05, 22, 03, 89, 75, 42, 66};
Int i, n=0, search=0;
Printf(“\n Enter number to search in an array : ”);
Scanf(“%d”, &n);
For(i=0;i<n-1;i++)
{
If(arr[i]==n)
{
Printf(“\n Given number is found…Search is successful=%d”,n);
Search=1;
Break;
}
}
If(search==0)
Printf(“\n Given number is found…Search is successful=%d”,n);
Return 0;
}
O/P:- Enter number to search in an array : 89
Given number is found…Search is successful= 89
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining