DS – Linear Search

Searching techniques

  • Searching is the concept of finding the specified element either in linear data structure or in non-linear data structure.
  • Linear data structures
    • Array
      • Linear Search
      • Binary Search
    • Linked List
      • Search in List
      • Hash Search
    • Tree
      • Search in BST
      • Search in AVL
      • ….

Linear search:

  • Finding an element in the given array.
  • Every time we compare the key element with index element.
  • If matches, returns the location as element found.
  • If not present, control returns with Error message.

Code:

#include<stdio.h>
int main()
{
            int arr[50], size, i, key, found=0;
            printf(“Enter length of elements : “);
            scanf(“%d”, &size);
           
            printf(“Enter %d elements : \n”, size);
            for(i=0 ; i<size ; i++)
            {
                        scanf(“%d”, &arr[i]);
            }
           
            printf(“Enter element to be searched :”);
            scanf(“%d”, &key);
           
            for(i=0 ; i<size ; i++)
            {
                        if(key == arr[i])
                        {
                                    printf(“Element %d found @ loc : %d \n”, arr[i], i);
                                    found=1;
                                    break;
                        }
            }
            if(!found)
                        printf(“Element not found \n”);
           
            return 0;          
};
Scroll to Top