C Program to search for an element using linear search

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What is a linear search?

In this program, we have to discuss the linear search of elements. For that, we have to know more about the linear searching of elements in an array. Linear search is also known as a sequential search. From the name itself, we can say that linear search is a method of searching for elements. It needs to check all elements one by one until the desired element is found.

In linear searching, it basically iterates through all the records in the table, and it stops only when the required result is found. We have to compare each element with the element to search until it is found or the array end.

The program's logic is to import the header libraries to use the inbuilt functions in c. First, declare the array table[20], i, low, mid, high, key, size as an integer data type. Then read the size of the array into the variable size.

Read the array elements using for loop from the user. Read the key-value and save that into the variable key. Set low=0, high=size-1. By using a while loop with the condition 'low<=high', then calculate mid=low+high/2. Check if key=table[mid] then display successful search and exit. If the key is not found then display the search as unsuccessful

ALGORITHM

STEP 1: Include the header files to use the built-in function in the C program.

STEP 2: Declare the variable table[20] ,i,low,mid,high,key,size as integer.

STEP 3: Read the size of the array into the variable size.

STEP 4: Read the elements of the array into table[i] using for loop.

STEP 5: Read the key value into the variable key.

STEP 6: Set low=0,and high=size-1.

STEP 7: By using while loop checks low<=high, then assign mid=low+high/2.

STEP 8: Check if key==table[mid] then display successful search and exit.Else do step 9.

STEP 9: If the key

STEP 10: If the key is not found, then display an unsuccessful search.

C Source Code

                                          #include <stdio.h>

void main() {
  int table[20];
  int i, low, mid, high, key, size;
  printf("Enter the size of an array\n");
  scanf("%d", & size);
  printf("Enter the array elements\n");
  for (i = 0; i < size; i++) {
    scanf("%d", & table[i]);
  }
  printf("Enter the key\n");
  scanf("%d", & key);
  low = 0; /* search begins */
  high = (size - 1);
  while (low <= high) {
    mid = (low + high) / 2;
    if (key == table[mid]) {
      printf("SUCCESSFUL SEARCH\n");
      return;
    }
    if (key < table[mid])
      high = mid - 1;
    else
      low = mid + 1;
  }
  printf("UNSUCCESSFUL SEARCH\n");
} /* End of main() */

                                      

OUTPUT

Enter the size of an array
5

Enter the array elements
12
36
45
78
99

Enter the key
45

SUCCESSFUL SEARCH