Linear Search algorithm

 Hello coders, 

Welcome Back! 


Today will look at the Linear search algorithm. 


Why we need a searching algorithm? 

In the data structure, the searching algorithm is used to find data eg. a number that is present in a given list If it is present then at what location it occurs.

There are two types of searching algorithms
1] Linear search
2] Binary search
We will look at the linear search algorithm. 


Algorithm for linear search algorithm- 

  • Define an array
  • Define a variable 'item', it stores the value that we want to search.
  • To get the location of the item we make flag = 0
  • Then iterate through every element of the array.
  • If array element == item, then increment flag value, else keep flag value equal to zero.
  • If the flag value is not equal to zero then print the flag value and message "Element found" else print "element not found".

Code for linear search algorithm- 

#include<stdio.h> 

int main()
{
    int arr[10] = {10,30,5,7,8,9,0,45,78,23};
    int n,flag; 
    printf("Enter the element you want to search: ");
    scanf("%d",&n);
    for(int i=0; i<10; i++)
    {
        if(arr[i]==n)
        {
            flag = i+1;
            break;
        }
        else 
        {
            flag =0;
        }
    }
    if(flag !=0)
    {
        printf("Element found at %d location",flag);
    }
    else
    {
        printf("Element not found!");
    }
}


If any doubts drop a comment! Always ready to clear them. 

Happy learning! 

Comments

Popular post