Arrays
Why are arraysrequired?
Arrays are useful because -
• Sorting and searching a value in an array is easier.
• Arrays are best to process multiple values quickly and easily.
• Arrays are good for storing multiple values in a single variable.
2.
C Program forLinear Search
• Linear Search is a sequential searching algorithm in C that is used to
find an element in a list. Linear Search compares each element of the
list with the key till the element is found or we reach the end of the
list.
Example
• Input: arr = {10, 50, 30, 70, 80, 60, 20, 90, 40},
• key: 30
3.
Linear Search Algorithm
Tosearch for the given element using linear search, follow the below
approach:
• Start traversing from the start of the dataset.
• Compare the current element with the key (element to be searched).
• If the element is equal to the key, return index.
• Else, increment the index and repeat the step 2 and 3.
• If we reach the end of the list without finding the element equal to the
key, return some value to represent that the element is not found
4.
How Linear SearchWorks?
The working of linear search is very simple.
Let’s take an array arr = {10, 50, 30, 70, 80, 60, 20, 90, 40}
and the key as 30.
// C programto implement linear search using
loop
#include <stdio.h>
int linearSearch(int* arr, int n, int key) {
// Starting the loop and looking for the key in arr
for (int i = 0; i < n; i++) {
// If key is found, return key
if (arr[i] == key) {
return i;
}
}
// If key is not found, return some value to
indicate
// end
return -1;
}
int main() {
int arr[] = { 10, 50, 30, 70, 80, 60, 20, 90, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
// Calling linearSearch() for arr with key = 43
int i = linearSearch(arr, n, key);
// printing result based on value returned by
// linearSearch()
if (i == -1)
printf("Key Not Found");
else
printf("Key Found at Index: %d", i);
return 0;
}
Editor's Notes
#2 Output: Key Found at Index: 2
Explanation: Start from index 0, compare each element with the key (30). When index 2 is reached, the element (30) matches the target value.