84. Find Minimum and Maximum in an Array

#include <stdio.h>
#include <stdint.h>

// Find min and max from array
void find_min_max(uint8_t *arr, uint8_t n, uint8_t *min, uint8_t *max) {
    *min = arr[0];
    *max = arr[0];

    for (uint8_t i = 1; i < n; i++) {
        if (arr[i] < *min) {
            *min = arr[i];
        }
        if (arr[i] > *max) {
            *max = arr[i];
        }
    }
}

int main() {
    uint8_t n;
    scanf("%hhu", &n);
    uint8_t arr[100];

    for (uint8_t i = 0; i < n; i++) {
        scanf("%hhu", &arr[i]);
    }

    uint8_t min_val, max_val;
    find_min_max(arr, n, &min_val, &max_val);

    printf("%hhu %hhu", min_val, max_val);
    return 0;
}

What’s the goal?

Find the smallest and largest values in the array using a single traversal.

Why it matters in firmware?

  • Sensor calibration: Min/max voltage, ADC readings
  • Performance monitoring: highest/lowest thresholds
  • Used in waveform analysis, signal peaks, buffer scan

Solution Logic

  • Initialize both min and max with the first element
  • Traverse the array once
  • Update min if current value is smaller
  • Update max if current value is larger
     
Loading...

Input

5 10 20 5 30 15

Expected Output

5 30