C++ Program to Implement Linear Search Algorithm

This C++ Program which implements linear search algorithm. The program takes in the number of elements of the vector of integers, takes the elements as input, takes in the element to be searched and goes through every element until the required element is reached.

Here is source code of the C++ program which implements linear search algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

/*

* C++ Program to Implement Linear Search Algorithm

*/

#include <iostream>

#include <vector>

/* Function to fill Vector */

void make_vector(std::vector<int>& v)

{

int num, val;

std::cout<<"Enter the number of elements in vector ";

std::cin>> num;

for(int i =0; i < num; i++)

{

std::cin>> val;

v.push_back(val);

}

}

/* Linear Search Function */

int lin_search(std::vector<int> v,int val)

{

int key =-1;

for(int i =0; i < v.size(); i++)

{

if(v[i]== val)

{

key = i;

break;

}

}

return key;

}

int main()

{

int key, val;

std::vector<int> v;

make_vector(v);

std::cout<<"Enter the number : ";

std::cin>> val;

key = lin_search(v, val);

if(key !=-1)

std::cout<<"\nElement "<< val

<<" is at position "<<++key;

else

std::cout<<"\nElement "<< val

<<" is not present";

}

$ g++ main.cpp
$ ./a.out
Enter the number of elements in vector 524102332
Enter the number : 4
Element 4 is at position 2

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

If you wish to look at all C++ Programming examples, go to C++ Programs.