How to Find Max Min in Array- Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Arrays · Lecture 7

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.

7
Arrays chapter
12 min
Read and practise
100%
Free forever

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 for loops and the if statement
  • 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 1read a[i]
step 2a[i] < lo ?yes: lo = a[i]no: keep lo
step 3a[i] > hi ?yes: hi = a[i]no: keep hi
step 4i++ and repeat until i reaches N

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.

ia[i]lo afterhi afterWhat happened
1498498512new low
2530498530new high
3877498877new high
4601498877no change
5120120877new low
6455120877no change
7903120903new high
87777903new low
964077903no change

Where the answers sit in the sample array

adc51249853087760112045590377640
resultindex 7 holds the HIGH value 903index 8 holds the LOW value 77

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  = 826

The 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 -3

The 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.

Watch out: seeding from 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

ApproachPasses over dataComparisonsExtra memoryKeeps original order?
One loop tracking lo and hi1at most 2(N-1)two variablesYes
Two separate loops22(N-1)two variablesYes
Sort first, read both endsmanyabout N log Ndepends on sortNo

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

MistakeSymptomFix
Seeding min or max with 0Wrong answer for all-negative or all-positive dataSeed from a[0] or use INT_MIN / INT_MAX
Loop condition i <= NReads one element past the array, random resultUse i < N
Comparison operators swappedMin and max come out reversedRead the test aloud: smaller replaces lo, larger replaces hi
Forgetting the indexYou know the value but not when it occurredStore the position next to the value
Computing hi – lo on extreme signed valuesSigned overflow, undefined behaviourUse 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, hi instead of a, 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

free c programming coursefree c tutorialc programming for embedded systemsembedded c programmingfree embedded c coursec arrays for beginnersfind max and min in arrayarray maximum minimum C programADC peak detection

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.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →