#include <stdio.h>
#include <stdint.h>
int linear_search(uint8_t *arr, uint8_t n, uint8_t key) {
uint8_t found = 0;
for(int i = 0; i < n; i++){
if(arr[i] == key){
found = 1;
return i;
}
}
if(!found){
return -1;
}
}
int main() {
uint8_t n, key;
scanf("%hhu", &n);
uint8_t arr[100];
for (uint8_t i = 0; i < n; i++) {
scanf("%hhu", &arr[i]);
}
scanf("%hhu", &key);
int index = linear_search(arr, n, key);
printf("%d", index);
return 0;
}
Solving Approach
Iterate through the array until an element matches the key, if match is found return the index, and set the flag "found" to 1 if not match is found flag 'found' won't change therefore returns -1;