Linear Search Program in C with Time complexity [New]

In this Linear search program in c, we will understand how to search elements in an array using for loop.
In this Linear search program in c, we will understand how to search elements in an array using for loop

    Linear Search Program in C

    #include<stdio.h>
    int main()
    {
        int arr[50],n,i,num;
        printf("Enter Size of Array:");
         scanf("%d",&n);
        printf("Enter elements of Array:");
        for( i = 0; i < n; i++)
        {
             scanf("%d",&arr[i]);
        }
        printf("Enter element for searching:");
         scanf("%d",&num);
        for ( i = 0; i < n; i++)
        {
             if(arr[i]==num)
            {
                 printf("Element found at index: %d",i);
                 printf("\nElement found at Position: %d",i+1);
                break;
            }
        }
        if(i==n)
         printf("Element not found");
    return 0;
    }

    Linear search program in C with time complexity
    Output:

    Enter Size of Array:5
    Enter elements of Array:66 78 56 25 45
    Enter element for searching:25
    Element found at index: 3
    Element found at Position: 4

    The linear search algorithm in c

    Case 1: The element to be searched is present in an array

    Case 2: The element to be searched is not present in an array


    1. Creating for loop, initializing i = 0; i < n; i++.
    2. Now, we will compare arr[i] & element to be searched.
    3. If they are equal, we will print “i”, which represents the index number. For position, print “i+1”.
    4. If the element to be searched is not present in an array, then i is equal to n.
    5. We will compare “i” & “n” if i is equal to n, then we have to print the element not found.

    Video explanation for linear search

    Linear search program in C with time complexity

    Best case time complexity linear search: O(1)

    Worst-case time complexity linear search: O(n)

    Average case time complexity linear search: O((n+1)/2)

    When can a linear search be used?

    We can use linear search in both sorted and unsorted arrays.

    How does linear search work?

    In linear search, we compare every array element with the targeted value. If that element is not in an array, it will print “Element not found”. If that element is present in the array, it will print index no. and the position of that element in the array.

    Let me know your doubts regarding the linear search program in c using for loop in the comment section.

    Post a Comment

    Please do not enter any spam link in the comment box.