C Program to Find Smallest Element in Array
for loop to compare and update it if a smaller element is found, like if (arr[i] < min) min = arr[i];.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int arr[] = {5, 3, 8, 1, 4}; int n = sizeof(arr) / sizeof(arr[0]); int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } printf("Smallest element is %d\n", min); return 0; }
Dry Run
Let's trace the array {5, 3, 8, 1, 4} through the code to find the smallest element.
Initialize min
min = 5 (first element)
Compare arr[1] = 3 with min = 5
3 < 5, so min = 3
Compare arr[2] = 8 with min = 3
8 < 3? No, min stays 3
Compare arr[3] = 1 with min = 3
1 < 3, so min = 1
Compare arr[4] = 4 with min = 1
4 < 1? No, min stays 1
End of array
Smallest element found is 1
| Index | Current Element | Current Min |
|---|---|---|
| 0 | 5 | 5 |
| 1 | 3 | 3 |
| 2 | 8 | 3 |
| 3 | 1 | 1 |
| 4 | 4 | 1 |
Why This Works
Step 1: Initialize minimum
We start by assuming the first element is the smallest using min = arr[0].
Step 2: Compare each element
We check each element with if (arr[i] < min) to find if there is a smaller value.
Step 3: Update minimum
If a smaller element is found, we update min to that element to keep track of the smallest value.
Alternative Approaches
#include <stdio.h> int main() { int arr[] = {5, 3, 8, 1, 4}; int n = sizeof(arr) / sizeof(arr[0]); int min = arr[0]; int i = 1; while (i < n) { if (arr[i] < min) { min = arr[i]; } i++; } printf("Smallest element is %d\n", min); return 0; }
#include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {5, 3, 8, 1, 4}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), compare); printf("Smallest element is %d\n", arr[0]); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once in a single loop, so it runs in linear time O(n), where n is the number of elements.
Space Complexity
It uses only a few extra variables and does not require extra space proportional to input size, so space complexity is O(1).
Which Approach is Fastest?
The direct loop approach is fastest for just finding the smallest element. Sorting is slower (O(n log n)) but useful if you need the array sorted.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Single loop comparison | O(n) | O(1) | Finding smallest element quickly |
| While loop | O(n) | O(1) | Same as for loop, different style |
| Sorting then picking first | O(n log n) | O(1) | When sorted array is also needed |