fork download
  1. // C program to implement linear search using loops
  2. #include <stdio.h>
  3.  
  4. // linear search function that searches the key in arr
  5. int linearSearch(int* arr, int size, int key)
  6. {
  7. // starting traversal
  8. for (int i = 0; i < size; i++) {
  9. // checking condition
  10. if (arr[i] == key) {
  11. return i;
  12. }
  13. }
  14. return -1;
  15. }
  16.  
  17. // Driver code
  18. int main()
  19. {
  20. int arr[10] = { 3, 4, 1, 7, 5, 8, 11, 42, 3, 13 };
  21. int size = sizeof(arr) / sizeof(arr[0]);
  22. int key = 4;
  23.  
  24. // calling linearSearch
  25. int index = linearSearch(arr, size, key);
  26.  
  27. // printing result based on value returned by
  28. // linearSearch()
  29. if (index == -1) {
  30. printf("The element is not present in the arr.");
  31. }
  32. else {
  33. printf("The element is present at arr[%d].", index);
  34. }
  35.  
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 5272KB
stdin
1
457
1
87
1
320
2
3
4
stdout
The element is present at arr[1].