C Program to Search Element in Array
if (arr[i] == key) and print the index if found.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5, key = 3, found = 0; for (int i = 0; i < n; i++) { if (arr[i] == key) { printf("Element %d found at index %d\n", key, i); found = 1; break; } } if (!found) { printf("Element %d not found in the array\n", key); } return 0; }
Dry Run
Let's trace searching for element 3 in array [1, 2, 3, 4, 5].
Start loop with i=0
Compare arr[0] = 1 with key = 3 (not equal)
Next loop with i=1
Compare arr[1] = 2 with key = 3 (not equal)
Next loop with i=2
Compare arr[2] = 3 with key = 3 (equal, found)
Print result and exit loop
Output: Element 3 found at index 2
| Index (i) | Array Value | Comparison Result |
|---|---|---|
| 0 | 1 | No match |
| 1 | 2 | No match |
| 2 | 3 | Match found |
Why This Works
Step 1: Loop through array
The program checks each element one by one using a for loop.
Step 2: Compare elements
Inside the loop, it uses if (arr[i] == key) to find a match.
Step 3: Print and stop
When a match is found, it prints the index and stops searching with break.
Step 4: Handle not found
If no match is found after the loop, it prints that the element is not in the array.
Alternative Approaches
#include <stdio.h> int search(int arr[], int n, int key) { for (int i = 0; i < n; i++) { if (arr[i] == key) return i; } return -1; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5, key = 3; int index = search(arr, n, key); if (index != -1) printf("Element %d found at index %d\n", key, index); else printf("Element %d not found in the array\n", key); return 0; }
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5, key = 3, found = 0; for (int i = 0; i < n; i++) { if (arr[i] == key) { printf("Element %d found at index %d\n", key, i); found = 1; } } if (!found) { printf("Element %d not found in the array\n", key); } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once in the worst case, so time grows linearly with array size.
Space Complexity
No extra space is used except a few variables, so space is constant.
Which Approach is Fastest?
Linear search with break is fastest for unsorted arrays; binary search is faster but requires sorted arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Linear search with break | O(n) | O(1) | Unsorted arrays, stop at first match |
| Linear search without break | O(n) | O(1) | Find all matches |
| Function-based search | O(n) | O(1) | Reusable code, clarity |
break to stop searching once the element is found to save time.