 C++ Tutorials

# C++ Tutorials

Linear Search (Searching algorithm) in C++ Program to Implement. Linear Search in C++ To search any given number/element present inside the array and if it is present then at what location it. C++ programming using linear search technique,

## Linear Search Algorithm using C++ Example with code

``````#include<bits/stdc++.h>
#include<iostream>

using namespace std;

int linearSearch(int arr[], int n, int key){
for(int i=0; i<n; i++){
if(arr[i]==key){
return i;
}
}
return -1;
}

int main(){
int n;
cout<<"Enter number of array: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cout<<"Enter "<<i+1<<" number of element in the linear search: ";
cin>>arr[i];
}
int key;
cout<<"Enter you want find number: ";
cin>>key;

cout<<"Index number: "<<linearSearch(arr,n,key)<<endl;

return 0 ;
}``````

Learn about linear search. Linear Search is a searching algorithm in which we sequentially check each and every element until we find the element we are looking for or we reach the last element and the element we are looking for is not present. So lets take an example, suppose this is the array of elements given to us and we are looking for the number 4, so the basic three steps that we will follow in linear search are : we will loop through the array from start till the end and we will check the value of every element wether it is equal to the element we are looking for and if we find that element we will return the index of that element, otherwise if we reach the end of the array it would simply mean that the element is not found.

So lets actually do this, so we start traversing the array from the beginning and we check the value at every index if it is equal to 4, at index 0 the value is 2 and it is not equal to 4, so we move on to the next element. The value at index 1 is equal to 3 so again we move on to the next element and the value at index 2 is equal to 7 which is not equal to 4 so again we move on to the next element and now the value at index 3 is equal to 4 which is the element we were looking for, so we will simply say that 4 is found at index 3.

Now let’s implement this using C++. So we start our LinearSearch function which takes the argument an array of integers ‘A’ , integer ‘n’ which is the size of the array or the number of elements and an integer ‘e’ which is the element to be searched and if the element ‘e’ is found in the array ‘A’ our function returns its index, otherwise it returns -1.

So firstly we declare two variables ‘i’ and ‘index’ and we initialise ‘index’ to -1 then we start our for loop using which we traverse the array ‘A’ from index 0 to index n-1 and at every index we check if the value of the element at index ‘i’ is equal to the value of ‘e’, then we store the index of the element in the variable ‘index’ and we break out of the loop and if the element is not present in the array ‘A’ after the loop ends the variable ‘index’ would have value -1 and we will return the value of ‘index’.