🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Find Max Min in Array
Find max and min in array data with one clean loop. Trace table, seed trap, index tracking and real ADC examples in our free C programming course.
In this lecture of our free C programming course you learn how to find max and min in array data using a single loop. It is the same logic your firmware uses to catch the peak of a sensor signal.
We build the algorithm from scratch, trace it on real numbers, show the classic bug that fails interviews, and run a tested program. Everything here is written for beginners moving toward embedded jobs.
What You Will Learn
- The running minimum and maximum idea
- Why the loop starts at index 1 and how to seed correctly
- Tracking the index of the largest and smallest values
- The all-negative data bug and how to avoid it
- Where peak detection is used in embedded systems
Prerequisites
- Previous lectures in this arrays chapter, especially array initialization
- Knowledge of
forloops and theifstatement - GCC or Clang installed on Linux, macOS or WSL
The Idea Behind Find Max and Min in Array
To find max and min in array data, you do not need sorting or any clever trick. You walk through the array once and keep two variables: the smallest value seen so far and the largest value seen so far. Every new element is compared with those two. If it beats one of them, that variable is replaced. When the loop ends, the variables hold the answers. This one-pass idea is used inside real firmware to track the peak of a signal without storing the whole signal.
Decision made for every element a[i]
Step-by-Step Trace on Ten ADC Samples
Imagine an ADC that returns ten readings: 512, 498, 530, 877, 601, 120, 455, 903, 77 and 640. We start by trusting the first reading for both variables, so lo = hi = 512. The loop then begins at index 1, because index 0 has already been looked at. Follow the table row by row.
| i | a[i] | lo after | hi after | What happened |
|---|---|---|---|---|
| 1 | 498 | 498 | 512 | new low |
| 2 | 530 | 498 | 530 | new high |
| 3 | 877 | 498 | 877 | new high |
| 4 | 601 | 498 | 877 | no change |
| 5 | 120 | 120 | 877 | new low |
| 6 | 455 | 120 | 877 | no change |
| 7 | 903 | 120 | 903 | new high |
| 8 | 77 | 77 | 903 | new low |
| 9 | 640 | 77 | 903 | no change |
Where the answers sit in the sample array
C Program to Find Max and Min in Array
The program below tracks not only the values but also where they were found, which is what a data logger really wants. The array length lives in a #define so the declaration and the loop can never disagree.
#include <stdio.h>
#define N_SAMPLES 10
int main(void)
{
int adc[N_SAMPLES] = {512, 498, 530, 877, 601, 120, 455, 903, 77, 640};
int lo = adc[0], hi = adc[0];
int lo_at = 0, hi_at = 0;
int i;
for (i = 1; i < N_SAMPLES; i++) {
if (adc[i] < lo) { lo = adc[i]; lo_at = i; }
if (adc[i] > hi) { hi = adc[i]; hi_at = i; }
}
printf("lowest = %d (index %d)\n", lo, lo_at);
printf("highest = %d (index %d)\n", hi, hi_at);
printf("spread = %d\n", hi - lo);
return 0;
}$ gcc -std=c17 -Wall -Wextra -o ep_adc_peak ep_adc_peak.c
$ ./ep_adc_peak
lowest = 77 (index 8)
highest = 903 (index 7)
spread = 826The output matches our trace: lowest 77 at index 8, highest 903 at index 7. The spread, 826, is the peak-to-peak amplitude of the signal, a number you will meet again when you measure vibration or ripple.
Why does the loop start at 1?
Both lo and hi were seeded from adc[0]. Comparing element 0 with itself can never change anything, so starting at index 1 saves one useless pass. Starting at 0 would still give the right answer; it is only a small optimisation, not a rule.
The Seed Trap: Why Starting at Zero Fails
Beginners often write int max = 0; because zero feels like a neutral start. It is not neutral if your data can be negative. Temperatures in a freezer, for instance, are all below zero, and a maximum seeded with 0 will never be replaced. Run this on purpose to see the bug.
#include <stdio.h>
int main(void)
{
int temp[5] = {-12, -7, -30, -3, -18};
int bad_max = 0; /* wrong seed: 0 is not in the data */
int good_max = temp[0]; /* right seed: a real element */
int i;
for (i = 0; i < 5; i++)
if (temp[i] > bad_max) bad_max = temp[i];
for (i = 1; i < 5; i++)
if (temp[i] > good_max) good_max = temp[i];
printf("wrong seed gives %d\n", bad_max);
printf("right seed gives %d\n", good_max);
return 0;
}$ gcc -std=c17 -Wall -Wextra -o ep_wrong_seed ep_wrong_seed.c
$ ./ep_wrong_seed
wrong seed gives 0
right seed gives -3The wrong version reports 0, a value that is not even in the array. The rule is simple: seed from a real element, or use the extreme limits from <limits.h>. With the limits approach, the minimum starts at INT_MAX and the maximum at INT_MIN, so any real value replaces them on the first comparison.
a[0] is only valid when the array has at least one element. If the length can be zero (for example a buffer that is still empty), check the length first and return an error instead of reading a[0].Single Pass Versus Other Approaches
| Approach | Passes over data | Comparisons | Extra memory | Keeps original order? |
|---|---|---|---|---|
| One loop tracking lo and hi | 1 | at most 2(N-1) | two variables | Yes |
| Two separate loops | 2 | 2(N-1) | two variables | Yes |
| Sort first, read both ends | many | about N log N | depends on sort | No |
Because lo never exceeds hi, a value that is a new minimum cannot also be a new maximum, so the second test can be written as else if and skipped when the first one fired. The saving is small, but it shows how thinking about the data removes work.
Real-World Uses in Embedded C Programming
- Peak detection: track the highest ADC reading of a microphone or vibration sensor over a sampling window.
- Battery monitoring: keep the lowest voltage seen during a motor start to size the power supply.
- Temperature alarms: compare the window maximum with a threshold instead of reacting to every noisy sample.
- Range checking: the spread (high minus low) tells you how noisy a sensor is before you design a filter.
- Auto-scaling: find min and max to map raw readings onto a 0 to 100 percent display bar.
Mistakes When You Find Max and Min in Array
| Mistake | Symptom | Fix |
|---|---|---|
| Seeding min or max with 0 | Wrong answer for all-negative or all-positive data | Seed from a[0] or use INT_MIN / INT_MAX |
Loop condition i <= N | Reads one element past the array, random result | Use i < N |
| Comparison operators swapped | Min and max come out reversed | Read the test aloud: smaller replaces lo, larger replaces hi |
| Forgetting the index | You know the value but not when it occurred | Store the position next to the value |
| Computing hi – lo on extreme signed values | Signed overflow, undefined behaviour | Use a wider type such as long long |
Best Practices, Performance and Safety
- Keep the array length in one named constant, and use it in the declaration and the loop.
- Declare the loop variable and the result variables as close to their use as possible, and name them
lo,hiinstead ofa,b. - Performance: the algorithm is linear, O(N) time and O(1) memory. On a Cortex-M this is a handful of instructions per sample, so it is safe to run inside a periodic task.
- Streaming data: you do not need to store the array at all. Update lo and hi as each sample arrives and save RAM.
- Security and robustness: never trust a length that arrives over UART or a network. Validate it against the real array size before looping, because an oversized value turns this harmless loop into an out-of-bounds read.
Summary and Key Takeaways
- To find max and min in array data, keep a running minimum and maximum and update them in one pass.
- Seed from a real element, never from an arbitrary 0.
- Start the loop at index 1 when you seeded from index 0.
- Record the index as well as the value when the position matters.
- The same idea works on streaming data without storing the array.
Conclusion
You can now find max and min in array data with a single clean loop, explain every step with a trace table, and avoid the seed bug that catches many students in interviews. This pattern is a core piece of embedded C programming, because almost every sensor task begins with a question like what was the highest value in this window. In the next lecture of this free C tutorial we reverse an array in place using two indices.
Topics Covered in This Free Embedded C Lecture
Frequently Asked Questions
How do I find the maximum and minimum in an array in C?
Seed two variables with the first element, loop from index 1, replace the minimum when a smaller value appears and the maximum when a larger one appears.
Why should I not initialize max to 0?
If every element is negative, 0 is larger than all of them and is never replaced, so the program reports a value that is not in the array.
Can I find both values in one loop?
Yes. One loop with two comparisons per element finds both, so you read the array only once.
What is the time complexity?
It is linear, O(N), because each element is visited once, and it needs only constant extra memory.
How do I get the position of the maximum?
Store the loop index in a second variable whenever you update the maximum, as the program in this lecture does with hi_at.
What if the array is empty?
Reading the first element would be out of bounds. Check that the length is greater than zero before you seed from a[0].
Continue the Free Embedded C Course
Next up: reversing the elements of an array in place. Try modifying today’s program to also report the average value before you move on.

2 Comments