C++ program to search an element using linear search in array
In this chapter of C++ program tutorial out task is:
-
Write a C++ program to search an element using linear search in array
C++ program to search an element using linear search
Below is the C++ program to search an element using linear search.
#include<iostream>
using namespace std;
void linearSearch(int arr[], int n, int x)
{
bool t = false;
cout<<"The position of element: "<<x<<" is/are in index ";
for(int i=0;i<n;i++){
if (arr[i] == x)
cout<<i<<"\t";
t = true;
}
if(t==false){
cout<<"Element not found\n";
}
}
int main()
{
int n,i,x;
cout<<"Enter the number of elements\n";
cin>>n;
int arr[n];
cout<<"Enter the elements of the array\n";
for(i=0;i<n;i++){
cin>>arr[i];
}
cout<<"Enter the element to be searched\n";
cin>>x;
linearSearch(arr, n, x);
return 0;
}
OUTPUT :
Enter the number of elements
7
Enter the elements of the array
12 34 13 65 23 10 15
Enter the element to be searched
10
The position of element: 10 is/are in index 5
EXPLANATION :
In the above program:
-
By calling the function linearSearch the array , number of element and the the element to searched are passed
-
Then in the function the iteration starts from 0 th element and it searches the element from passing one by one index
-
When the element to be searched matches with the array element then the index is displayed.
WORKING :
arr[] = {12 , 34, 13, 65, 23, 10, 15}
n = 7
x = 10
1st iteration
if(arr[i] == x) // 12 == 10 -> false
2nd iteration
if(arr[i] == x) // 34 == 10 -> false
3rd iteration
if(arr[i] == x) // 13 == 10 -> false
4th iteration
if(arr[i] == x) // 65 == 10 -> false
5th iteration
if(arr[i] == x) // 23 == 10 -> false
6th iteration
if(arr[i] == x) // 10 == 10 -> true [index 5 returned]
7th iteration
if(arr[i] == x) // 15 == 10 -> false
The loop ends with this.
Time complexity:
O(n)
You can see the above code execution and output in codeblocks IDE:
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sayantan Bose
- š Iām currently working on DS Algo skills
- š± Iām currently learning web develeopement
- šÆ Iām looking to collaborate with Oppia
- š« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/
- š Pronouns: his/him
Page Views :
Published Date :
Aug 31,2020