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:
Prompts the user to enter the array size and elements.
Takes the value to search as user input.
Iterates through the array using a for loop, comparing each element with the search value.
If the value is found, it prints the index and sets the found flag to 1.
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.
Коментарі