searching – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 14:10:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg searching – Programmerbay https://programmerbay.com 32 32 C Program to Find an Element Using Linear Search https://programmerbay.com/program-to-search-an-element-using-linear-search/ https://programmerbay.com/program-to-search-an-element-using-linear-search/#respond Fri, 12 Jun 2020 09:49:18 +0000 https://www.programmerbay.com/?p=2912 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

linear search

When element is not exist

linear search 2

How does Linear Search work?

linear search working

]]>
https://programmerbay.com/program-to-search-an-element-using-linear-search/feed/ 0