Introduction

Linear search is a straightforward algorithm for finding a specific value within an array. It sequentially checks each element until the desired value is found or the end of the array is reached. This method is simple to implement but not the most efficient for large datasets.

#include <stdio.h>

int linearSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i; // Return the index if found
        }
    }
    return -1; // Return -1 if not found
}

int main() {
    int arr[] = {2, 4, 6, 8, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target;

    printf("Enter the number to search: ");
    scanf("%d", &target);

    int result = linearSearch(arr, size, target);

    if (result != -1) {
        printf("Element found at index: %d\n", result);
    } else {
        printf("Element not found in the array.\n");
    }

    return 0;
}

Explanation

  1. Function Definition:
    • linearSearch(int arr[], int size, int target): Takes an array, its size, and the target value to search for.
    • The function iterates over each element in the array.
  2. Loop:
    • A for loop is used to traverse the array. If an element matches the target, its index is returned.
  3. Return Values:
    • Returns the index of the target if found.
    • Returns -1 if the target is not found.
  4. Main Function:
    • Initializes an array and gets user input for the target value.
    • Calls linear Search and prints the result based on the return value.

Input

When you run the program, it prompts the user to enter a number to search for. For example:

Enter the number to search: 6

Output

The output will indicate whether the element was found and, if so, at which index

Element found at index: 2

Or if the element is not found:

Element not found in the array.

Conclusion

Linear search is an intuitive method for searching elements in an array. While its time complexity is O(n), making it less efficient for large arrays compared to algorithms like binary search, it remains a useful approach for small datasets or unsorted arrays where more advanced techniques cannot be applied. The simplicity of implementation and understanding makes it a good choice for educational purposes and basic applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights