- How the running-minimum pattern mirrors the running-maximum
- Why the initialization choice matters when all values are positive
- How the same function template serves for min, max, and other reductions
- How to combine min and max in a single pass
- How to handle the edge case of an empty array
The running-minimum pattern
Finding the minimum of an array is the mirror image of finding the maximum. The algorithm: keep a variable that holds "the smallest value seen so far," initialize it to the first element, then walk through the rest of the array and update the variable whenever you find something smaller. At the end, the variable holds the overall minimum. Same loop, one flipped comparison — everything else is identical.
This symmetry is worth noticing because it's a pattern that recurs in programming. Many operations — max, min, sum, product, count, find-first, find-last, any-match, all-match — follow the same shape: initialize an accumulator, iterate over the elements, update the accumulator based on a condition. The specific accumulator and update rule differ, but the loop structure is the same. Once you've internalized one, you've internalized the family.
The subtle part is initialization. For finding the maximum, you initialize to the first element (or to INT_MIN if you want a sentinel). For finding the minimum, you initialize to the first element (or to INT_MAX if you want a sentinel). Initializing to 0 is wrong in both cases — for max, it fails when all values are negative; for min, it fails when all values are positive. The safe rule is: initialize to a value that's guaranteed to be no worse than the true answer, which usually means initializing to the first element.
Another consideration: the array parameter should be const, since the function only reads from it. This protects against accidental modification and documents the function's intent. The size must be passed separately, because arrays decay to pointers when passed to functions. These are the same considerations as the max function — because, structurally, this is the same function.
💡 In one line: set min = arr[0], then for each i from 1 to n-1, if arr[i] < min, set min = arr[i]. After the loop, min is the smallest element. Swap < for > and you have the max function.
Designing the findMin function
The signature is the same pattern as findMax — parameterized array, explicit size, const protection:
| Part | Choice | Why |
|---|---|---|
| Function name | findMin | Mirrors findMax. Alternative: arrayMin, getMin. |
| Array parameter | const int arr[] | Read-only access. Declared as const so the compiler prevents modification. |
| Size parameter | int n | Required because arrays decay to pointers — the size can't be recovered from the pointer. |
| Return type | int | Returns the smallest element. |
The prototype:
int findMin(const int arr[], int n);
And the definition:
int findMin(const int arr[], int n) {
int min = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
Line for line, this is findMax with the comparison flipped: < instead of >, and min instead of max. If you've already written findMax (which is the previous assignment), you have this function almost for free — the only change is one character in the comparison. This is a common pattern in C: many algorithms are near-mirrors of each other.
And here's a version that computes both the min and max in a single pass — useful when you need both and want to avoid two separate loops:
void findMinMax(const int arr[], int n, int *outMin, int *outMax) {
*outMin = arr[0];
*outMax = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < *outMin) *outMin = arr[i];
if (arr[i] > *outMax) *outMax = arr[i];
}
}
This function uses pointer output parameters — instead of returning a single value, it writes the min and max into the locations pointed to by outMin and outMax. The caller passes addresses (findMinMax(arr, n, &mn, &mx)) and gets both results back. This is the C convention for returning multiple values — the same trick as the swap function from assignment 9. It's a bit more verbose than two separate functions, but for large arrays, doing both in one pass is roughly twice as fast.
🎯 Key idea: the min function is the max function with one comparison flipped. Once you see this, you can parameterize — a single generic "reduce" helper could handle min, max, sum, product, and more, given the right operation. That's the seed of higher-order functions, though C makes them a bit awkward (function pointers, no closures).
Complete C Program
Program: read an array, find the minimum
#include <stdio.h>
/* Function prototype */
int findMin(const int arr[], int n);
int main(void) {
int arr[100];
int n;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Please enter a valid count between 1 and 100.\n");
return 1;
}
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
printf("Minimum: %d\n", findMin(arr, n));
return 0;
}
/* Find the smallest element */
int findMin(const int arr[], int n) {
int min = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
And a version that shows both min and max in a single pass — the practical version when you need both:
Variant: min and max in one pass
#include <stdio.h>
void findMinMax(const int arr[], int n, int *outMin, int *outMax) {
*outMin = arr[0];
*outMax = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < *outMin) *outMin = arr[i];
if (arr[i] > *outMax) *outMax = arr[i];
}
}
int main(void) {
int arr[100], n;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0) return 1;
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
int mn, mx;
findMinMax(arr, n, &mn, &mx);
printf("Minimum: %d\n", mn);
printf("Maximum: %d\n", mx);
return 0;
}
One loop, two comparisons per iteration, two results. For large arrays, this is roughly twice as fast as calling findMin and findMax separately — each of those does its own loop with one comparison. If you need both values, combine them.
And a version that returns the index of the minimum — useful when you need to know where the minimum is, not just what it is:
Variant: return the index of the minimum
#include <stdio.h>
int findMinIndex(const int arr[], int n) {
int idx = 0;
for (int i = 1; i < n; i++) {
if (arr[i] < arr[idx]) {
idx = i;
}
}
return idx;
}
int main(void) {
int arr[100], n;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0) return 1;
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
int idx = findMinIndex(arr, n);
printf("Min value: %d at index %d\n", arr[idx], idx);
return 0;
}
Same pattern as findMaxIndex from the previous assignment, just with < instead of >. This returns the index of the first occurrence of the minimum — subsequent equal values don't update, because of the strict < comparison. If you wanted the last occurrence, use <=.
Program Output
A typical run:
How many elements? 5
Enter 5 integers: 3 7 2 9 4
Minimum: 2
With all positive numbers — the case where initializing to 0 would be wrong:
How many elements? 4
Enter 4 integers: 10 25 15 40
Minimum: 10
If we'd initialized min to 0 (thinking "0 is a small number"), then the comparison arr[i] < 0 would be false for all positive values, and the function would incorrectly return 0. Initializing to arr[0] avoids that.
With negative numbers:
How many elements? 5
Enter 5 integers: -3 -7 -2 -9 -4
Minimum: -9
The most negative number wins, which is correct.
With a single element:
How many elements? 1
Enter 1 integers: 42
Minimum: 42
The loop doesn't execute (since n = 1 and the loop starts at i = 1), and arr[0] is returned. Correct.
With the min-and-max variant:
How many elements? 6
Enter 6 integers: 3 1 4 1 5 9
Minimum: 1
Maximum: 9
Both values found in a single pass. Note that there are two 1s — the min function correctly reports 1, which is both occurrences. If you needed to know that, you'd use findMinIndex (returning index 1, the first occurrence) or findMaxIndex-with-<= to get the last.
With the index variant:
How many elements? 5
Enter 5 integers: 8 3 6 3 9
Min value: 3 at index 1
Two equal 3s at indices 1 and 3. The function returns index 1 — the first occurrence — because the strict < comparison doesn't update on equal values.
Step-by-Step Explanation
Let's trace the algorithm and then look at how it mirrors the max function.
1. Initialization: min = arr[0]
Same reasoning as the max function: arr[0] is the first element, so it's trivially the smallest element seen so far. If we initialized to a large sentinel like INT_MAX (from <limits.h>), that would also work — the first comparison would update min unless arr[0] == INT_MAX itself, in which case INT_MAX is the answer anyway. Both choices are correct. Initializing to arr[0] is simpler and more intuitive.
2. The loop starts at 1
We've already considered arr[0], so we start the scan at index 1. The loop runs n - 1 iterations, doing one comparison and possibly one update per iteration.
3. The comparison and update
if (arr[i] < min) min = arr[i]; — for each element, check if it's smaller than the current minimum. If so, it becomes the new minimum. Strictly less than (not ≤) means equal values don't trigger an update, which is fine for finding the value (the value is the same either way) and slightly better if you ever extend the function to track the index (first occurrence is preserved).
4. Tracing findMin({3, 7, 2, 9, 4}, 5)
- min = arr[0] = 3.
- i = 1: arr[1] = 7. 7 < 3? No. min stays 3.
- i = 2: arr[2] = 2. 2 < 3? Yes. min = 2.
- i = 3: arr[3] = 9. 9 < 2? No. min stays 2.
- i = 4: arr[4] = 4. 4 < 2? No. min stays 2.
- Loop ends. Return 2. ✓
5. Tracing findMin({10, 25, 15, 40}, 4)
- min = arr[0] = 10.
- i = 1: arr[1] = 25. 25 < 10? No.
- i = 2: arr[2] = 15. 15 < 10? No.
- i = 3: arr[3] = 40. 40 < 10? No.
- Loop ends. Return 10. ✓
The min stays at the first element because none of the others are smaller. This is a worst case for updates (zero updates), but the loop still runs all comparisons. If you'd initialized min = 0, all comparisons would fail (since all values are positive), and the function would incorrectly return 0 — which isn't even in the array.
6. Why this mirrors findMax
Put the two side by side:
int findMax(const int arr[], int n) { int findMin(const int arr[], int n) {
int max = arr[0]; int min = arr[0];
for (int i = 1; i < n; i++) { for (int i = 1; i < n; i++) {
if (arr[i] > max) { if (arr[i] < min) {
max = arr[i]; min = arr[i];
} }
} }
return max; return min;
} }
Identical structure. One comparison flipped. This is a consequence of a deep fact: max and min are "dual" operations — they're related by negating the values. min(x, y) = -max(-x, -y). So the algorithms mirror each other.
7. The empty-array case
If n == 0, our function would try to read arr[0] on an empty array — undefined behavior. Our program rejects n <= 0 in the caller, so the function's precondition is n ≥ 1. This is a clean division of responsibility: the function assumes a valid input, and the caller validates. In production code, you might want both — a defensive check inside the function AND a caller-side validation — to catch bugs from either direction. But for a learning program, one check is enough.
8. Why const matters here
Same reason as the max function: const int arr[] means the function won't modify the array. The compiler enforces this. It also documents the function's intent — it's a pure query, not a mutation. For a function that only reads, const is always the right choice. It's a small thing, but it adds up: functions that are const-correct are easier to reason about, and easier to pass through layers of abstraction without worrying about what each layer might do to your data.
9. Complexity
O(n) time, O(1) extra space. The loop visits each element once. There's no way to be faster without additional assumptions about the array — you have to look at every element to be sure it's not smaller than the current minimum. This is optimal for a general-purpose minimum function.
10. Combining min and max
The findMinMax variant computes both values in a single pass. Two comparisons per iteration, but only one loop — which means only one traversal of the array. For large arrays, this is significantly faster than two separate loops. The tradeoff is a slightly more complex function (two output pointers instead of a return value), but for a common operation like "find the range of these values," it's worth it. This is the kind of small optimization that accumulates into faster programs over time.
🔍 Try this: write a single function findRange(arr, n) that returns max - min — the range of the values. It's one pass, two tracking variables, one subtraction at the end. Then write findMean(arr, n) and findMedian(arr, n). Each has its own character, but they all use the same loop skeleton. Once you've built them, you have a small statistics library — max, min, range, mean, median — all in a handful of functions.
Frequently Asked Questions
1. Why is the min function different from the max function?
It's not, really — it's the same function with one comparison flipped. The algorithm is identical: initialize to the first element, loop through the rest, update on a better value. The only difference is whether "better" means "larger" (max) or "smaller" (min), and that's encoded in the single comparison operator. Recognizing this symmetry is a good way to see that many "different" functions are actually the same pattern in disguise.
2. What if all elements are positive and I initialize min to 0?
The function would return 0 — but 0 isn't even in the array. Because arr[i] < 0 is always false for positive values, min never updates from its initial 0. This is exactly the kind of bug you avoid by initializing to arr[0] instead. The pattern is: "initialize to a value that could plausibly be the answer, not to a sentinel that's obviously out of range." Initializing to arr[0] is the simplest correct choice.
3. What if the array is empty?
Our function would crash on arr[0] — reading past the end of a zero-length array is undefined behavior. To handle this, either add a check if (n == 0) return INT_MAX; inside the function (though INT_MAX might be a real value in the array, making it ambiguous), or validate in the caller (which our program does). The latter is cleaner: the function has a simple contract ("n ≥ 1"), and the caller ensures it. This is the standard division of labor in C.
4. How do I find both the minimum and the maximum efficiently?
Use the findMinMax variant shown above. It does two comparisons per element but visits each element only once, so it's roughly twice as fast as two separate loops. The function takes two output pointers (outMin, outMax), and the caller passes the addresses of two local variables to receive the results. This is the C convention for returning multiple values — the same pattern as the swap function.
5. Can I find the minimum of an array without a loop?
Not with standard C. You could use recursion (min(arr, n) = min(arr[0], min(arr+1, n-1))), but that's just the loop expressed recursively — same complexity, more stack usage. Or you could use qsort and take arr[0], but that's O(n log n), much slower than a single O(n) scan. The linear scan is the right tool. Don't overthink it.
6. Can I find the k-th smallest element in an array?
Yes, but it requires more than a simple scan. Two common approaches: (a) sort the array and take the k-th element — O(n log n); (b) use quickselect, a variant of quicksort that only recurses into the partition containing the k-th element — O(n) average case. For small arrays, sorting is fine. For large arrays where you need k-th order statistics repeatedly, quickselect (or a heap-based approach) is more efficient. This is a natural extension of the min/max problem, and a good next step after you've mastered the simple scan.
💡 Tip: Once this works, combine it with findMax to write findRange(arr, n) — the difference between the max and min. Then extend to findMean (sum divided by count) and findMedian (requires sorting or quickselect). Each is a small, well-defined function, and together they form a small statistics library. Once you have a toolkit like that, you can solve a huge range of array-processing problems with the same simple building blocks.