C Program to search an element using linear search technique
ALGORITHM :
Step 1: Start
Step 2: Input the number of elements (n) and the list of elements (my_list).
Step 3: Input the element to be searched (key).
Step 4: Initialize a variable (position) to -1 to store the position of the element.
Step 5: Repeat the following steps for i = 0 to n-1:
a. If my_list[i] is equal to the key, set position to i and break the loop.
Step 6: If position is not equal to -1, display "Element found at position: position+1".
Otherwise, display "Element not found in the list".
Step 7: End
SOURCE CODE :
#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i;
}
return -1;
}
int main() {
int n, key;
printf("Enter the number of elements in the list: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &key);
int index = linearSearch(arr, n, key);
if (index != -1)
printf("Element found at index %d\n", index);
else
printf("Element not found in the list.\n");
return 0;
}
OUTPUT
Enter the number of elements in the list: 5
Enter 5 elements: 25 18 42 36 12
Enter the element to search: 36
Element found at index 3
It is helpfull and so nice
ReplyDelete