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; // Return the index of the target element if found
}
}
return -1; // Return -1 if the target element is not found
}
int main()
{
int arr[100];
int n, i, target, result;
/*
* Read size of array and elements in array
*/
printf("Enter size of array :: ");
scanf("%d", &n);
printf("\nEnter elements in array: \n");
for(i=0; i<n; i++)
{
printf("Enter %d element in array :: ",i+1);
scanf("%d", &arr[i]);
}
printf("\nEnter the element to search within the array: ");
scanf("%d", &target);
/* call the linear search function */
result = linearSearch(arr, n, target);
if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the list.\n", target);
}
return 0;
}
Comments
Post a Comment