C Program to Find an Element Using Linear Search

Share

The program simply searches an element in the given array and prints it on output screen using linear search searching technique.

Linear Search

Linear search is a searching technique to check whether an element is present in the given list or not.

It checks for the user’s input element existence in the given list by sequentially comparing all the elements of the array one by one, if a match is found then it would return the position of the desired element.

It requires O(n) time to search a given element in the worst case scenario. It is also known as Sequential Search.

Pseudocode

FOR position=0 to Array.length
IF Array[position] = ElementToSearch
return position+1
END IF 
END FOR

C program to search an element in an array using Linear search

/**

C program to search an element using Linear Search
**/
#include<stdio.h>
#define size 5

int linearSearch (int arr[], int element)
{
  int i, position = -1;
  for (i = 0; i < size; i++)
    {
      if (element == arr[i])
  {
    position = i;
    break;
  }
    }
  return position;
}

int main ()
{
  int arr[size], element;
  int i, position;
  printf ("\nPlease enter 5 elements : ");
  for (i = 0; i < size; i++)
    {
      scanf ("%d", &arr[i]);
    }
  printf ("\n Please enter an element to search in list: ");
  scanf ("%d", &element);
  position = linearSearch (arr, element);

  if (position != -1)
    printf ("\n your element found at : %d position and the number was %d ",
      position + 1, arr[position]);
  else
    printf ("element is not found");

  return 0;
}

Output:

When element is exist

When element is not exist

How does Linear Search work?

This post was last modified on December 27, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: algorithm C c program C Program to search an element in an array using linear search linear search linear search c program search an element in an array using linear search searching sequential search