The Art of Writing Short Stories Read Here

Tutorial Linear Search in C++ , Programming

Linear Search in C++

Objective: To search for a particular value in an array. If the value is present then return the position of the value in the array.

linear search free c++ program tutorial for begginers
Linear Search

How:

As the word ‘Linear’ suggests, the array will be traversed linearly; means all the elements of the array will be visited one by one in the order of their storage.
If the array is Num[5], the order of visiting the arrays elements to compare the value to be searched will be:
Num[0] -> Num[1] -> Num[2] -> Num[3] -> Num[4]

Code:

#‎include <cstdlib>
#include <iostream>
#include <stdio>

using namespace std;
int main()
{

int arr[100], i, n, searchValue, result=0;
//Ask for the size of array to be used
cout<<"Enter No. of Elements to be stored ";
cin>>n; // n is the total number of values that will be stored, n<=100

// Ask the user to input values, Input Loop
for(i=0;i<=n-1;i++) // Loop will be executed ‘n’ times to store ‘n’ number of values
{ cout<<"Enter the element "<<i+1<<" ";
cin>>arr[i];
}

//Ask the user the value to be searched
cout<<"\nEnter value you want to search ";
cin>>searchValue;

//Loop will compare the value to be searched with each element in the array one by one in each iteration, Search Loop
for(i=0; i<=n-1; i++)
{
if(arr[i]==searchValue) // Comparison of values
{
cout<<"\nValue is stored at location : "<<i+1; // Out if value is present
result=1; // Result if value is present
break; // Stop the loop execution if the value is found
}
}

if(result==0)
{
cout<<"Value not available"; // Output if value is not present
}

}

Output:
Enter No. of Elements to be stored 5

Enter the element 1 8
Enter the element 2 3
Enter the element 3 6
Enter the element 4 5
Enter the element 5 9

Enter value you want to search=3
Value is stored at location : 2

Thanks @codebasics
You may also like :