top of page
Writer's picturecompnomics

C Program Demonstrating Linear Search in an Array

Here's a C program that demonstrates linear search in an array:

#include <stdio.h>

int main() {
    int arr[100], size, search_value, found = 0;

    // Get array size from user
    printf("Enter the size of the array (max 100): ");
    scanf("%d", &size);

    // Get array elements from user
    printf("Enter %d integers:\n", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    // Get the value to search
    printf("Enter the value to search: ");
    scanf("%d", &search_value);

    // Linear search implementation
    for (int i = 0; i < size; i++) {
        if (arr[i] == search_value) {
            printf("Value found at index %d!\n", i);
            found = 1;
            break; // Terminate search upon finding the value
        }
    }

    if (!found) {
        printf("Value not found in the array.\n");
    }

    return 0;
}

This program:

  1. Prompts the user to enter the array size and elements.

  2. Takes the value to search as user input.

  3. Iterates through the array using a for loop, comparing each element with the search value.

  4. If the value is found, it prints the index and sets the found flag to 1.

  5. If the loop completes without finding the value, it prints a message indicating that the value is not present.

This program showcases the basic logic of linear search, which iterates through all elements sequentially until the target is found or the end of the array is reached.

57 views0 comments

Коментарі

Оцінка: 0 з 5 зірок.
Ще немає оцінок

Додайте оцінку
bottom of page