SY_Linear search

 #include <stdio.h>


int linearSearch(int arr[], int n, int target) {

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

        if (arr[i] == target)

            return i; // Element found, return index

    }

    

    return -1; // Element not found

}


int main() {

    int n;

    printf("Enter the number of elements in the array: ");

    scanf("%d", &n);

    

    int arr[n];

    printf("Enter the elements of the array:\n");

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

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

    }

    

    int target;

    printf("Enter the value to search for: ");

    scanf("%d", &target);

    

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

    

    if (result == -1)

        printf("Element not found\n");

    else

        printf("Element found at index %d\n"

, result);

    

    return 0;

}

Post a Comment

Previous Post Next Post