C/C++ Program for Linear Search?



What is Linear Search?

Linear search is a sequential searching technique in which we start at one end of the list or array and look at each element until the target element is found. It is the simplest searching algorithm, with O(n) time complexity.

Example Scenario

let's see the following example scenario:

Input: arr = {5, 4, 3, 8, 10}, K = 3;
Output: 3 found at index 2;

Input: arr = {1, 2, 3, 4, 5}, K = 7;
Output: Not Found;

How Linear Search Work?

Following are the steps to search an element in array or list:

  • Iterate through a loop in the range i=0 to the length of the array.
  • Start from the first element and compare k with each element of an array.
  • If arr[i] == k, return the index.
  • Else, return not found.

Linear Search Algorithm

Following is the linear search algorithm:

linear_search(array, key)
   for each item in the array
      if item == value
         return its index

C++ Program for Linear Search

In the following example, using the linear search to search for an element in an array using C++:

#include <iostream>
using namespace std;
void linear_search(int arr[], int len, int K) {
   bool found = false;
   for (int i = 0; i < len; i++) {
      if (arr[i] == K) {
         cout << K << " found at index " << i << endl;
         found = true;
         break;
      }
   }
   if (!found) {
      cout << "Not Found" << endl;
   }
}
int main() {
   int arr[] = { 5, 4, 3, 8, 10 };
   int K = 3;
   int len = sizeof(arr) / sizeof(arr[0]);
   linear_search(arr, len, K);
   return 0;
}

Following is the output:

3 found at index 2
Updated on: 2025-06-30T13:17:38+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements