C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Linear Search Program

C Program: Linear Search Program

Method 1: Using for loop

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i, key, found = 0;

 

    // Input size of the array

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for(i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Input element to search

    printf("Enter element to search: ");

    scanf("%d", &key);

 

    // Linear Search

    for(i = 0; i < n; i++) {

        if(arr[i] == key) {

            printf("\nElement %d found at position %d\n", key, i + 1);

            found = 1;

            break;

        }

    }

 

    if(!found)

        printf("\nElement %d not found in the array\n", key);

 

    return 0;

}

Output

 
INPUT :
Enter number of elements: 5
Enter 5 elements:
12 45 7 23 9
Enter element to search: 23

OUTPUT :
Element 23 found at position 4

Explanation

  1. The user enters the number of elements and the array values.
  2. The program then asks for the element to search (key).
  3. Using a for loop, each array element is compared with key.
  4. If a match is found, the position (index + 1) is printed, and the search stops.
  5. If no match is found after checking all elements, it displays “not found.”

 

C Program: Linear Search Program

Method 2: Using while loop

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i = 0, key, found = 0;

 

    // Input size of the array

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    while(i < n) {

        scanf("%d", &arr[i]);

        i++;

    }

 

    // Input element to search

    printf("Enter element to search: ");

    scanf("%d", &key);

 

    // Reset counter for search

    i = 0;

 

    // Linear search using while loop

    while(i < n) {

        if(arr[i] == key) {

            printf("\nElement %d found at position %d\n", key, i + 1);

            found = 1;

            break;

        }

        i++;

    }

 

    if(!found)

        printf("\nElement %d not found in the array\n", key);

 

    return 0;

}

Output

 
INPUT :
Enter number of elements: 6
Enter 6 elements:
5 8 12 45 67 90
Enter element to search: 45

OUTPUT :
Element 45 found at position 4

Explanation

  1. The user first inputs the number of elements (n) and array values.
  2. A while loop is used to read all elements.
  3. After taking input, another while loop searches for the given key.
  4. If the element matches, it displays the position and stops.
  5. If not found after traversing all elements, it prints a “not found” message.