Find Maximum Value of an Array in C

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
Arrays

What You’ll Learn

Finding the maximum in an unsorted array is a classic linear scan: keep a running winner and update it whenever you see a larger value. This tutorial covers find_max, sizeof for length, a live preview, worked C examples (mixed positives and all negatives), edge cases, and O(n) complexity.

Running Max

Start at arr[0]

Pick the first element, then beat it with larger values.

One Pass

Left → right

Visit each index once — no sorting required.

find_max

Reusable helper

Pass the array and size; return the largest value.

Negatives OK

Still works

All-negative arrays: the max is the least negative.

Live Preview

Max = 42

Same six numbers as Example 1, computed in the browser.

O(n)

O(1) space

Optimal for an unsorted scan; mention empty-array edges.

Introduction

To find the maximum in a 1D array, pick the first element as your provisional winner. For each next element, if it is greater than the current winner, replace the winner. After the last index, the winner is the maximum.

This is one pass, left to right — easy to code and easy to explain in an interview. No sorting required.

Why it matters?

It is the foundational array scan: running state, comparisons, and O(n) reasoning — skills reused for min, average, and search problems.

Key Highlights

Init from arr[0]

Never seed with a magic constant.

Compare with >

Update only when the next value is larger.

sizeof Length

Count elements without hard-coding.

O(n) / O(1)

One pass; constant extra space.

In short: set max = arr[0], then for each later element if arr[i] > max update max — and require size >= 1.

📝 Problem & Approach

Given a non-empty array of integers, return the largest value with a single left-to-right scan.

c
/* Array: 14, 7, 25, 31, 10, 42
 * Start max = 14
 * 25 > 14 → max = 25
 * 31 > 25 → max = 31
 * 42 > 31 → max = 42
 */

Inputs & Outputs

ItemTypeDescription
arrconst int[]Input array; not modified by find_max.
sizeintElement count; must be >= 1 for this tutorial.
returnintLargest value among the size elements.

Minimal workflow

Pseudocode
function find_max(arr, size):   // assume size >= 1
    max ← arr[0]
    for i from 1 to size - 1:
        if arr[i] > max:
            max ← arr[i]
    return max

Method comparison

ApproachCostNotes
Linear scan (this page)O(n)Best for max alone
Sort then take lastO(n log n)Overkill for max only
Find minimumO(n)Same loops; use < instead

⚡ Quick Reference

GoalPattern
Initializemax_val = arr[0];
Updateif (arr[i] > max_val) max_val = arr[i];
Lengthsizeof(array) / sizeof(array[0])
GuardRequire size >= 1 before reading arr[0]
CostO(n) time, O(1) extra space

📋 Max vs Min vs Sort

Related array problems — only max and min share the same single-pass structure.

Maximum
if > update

This page — running max

Minimum
if < update

Next page — flip the test

Sort then last
O(n log n)

Unnecessary for max alone

Interview tip
arr[0] seed

Avoid INT_MIN unless asked

Context

When This Problem Shows Up

Reach for a running maximum whenever you need the largest value in an unsorted list.

  1. Interview warm-up

    First array question for many beginners.

  2. Scores / sensors

    Highest reading in a batch of samples.

  3. Building block

    Basis for min, range, and clamp helpers.

  4. Contrast with sort

    Show why O(n) beats sorting for this goal.

  5. Not for empty arrays

    Validate size before reading arr[0].

Key benefit: one clear scan that proves you understand running state, comparisons, and complexity without overengineering.

🔮 Live Preview

Uses the same six integers as Example 1: 14, 7, 25, 31, 10, 42.

Runs the same comparison logic in JavaScript.

Live result
Press “Find maximum”.

Examples Gallery

Two complete C programs — a mixed positive sample (max 42) and an all-negative demo (max -1). Click View Output to reveal sample console results.

📚 Getting Started

Initialize from the first element, then scan with >.

Example 1 — Find Maximum (Reference Program)

Matches the classic walkthrough: find_max, sample array, and sizeof length. Uses int main(void).

c
#include <stdio.h>

int find_max(const int arr[], int size) {
    int max_val = arr[0];

    for (int i = 1; i < size; ++i) {
        if (arr[i] > max_val) {
            max_val = arr[i];
        }
    }

    return max_val;
}

int main(void) {
    int array[] = {14, 7, 25, 31, 10, 42};
    int size = (int)(sizeof(array) / sizeof(array[0]));
    int max_value = find_max(array, size);

    printf("Maximum value in the array: %d\n", max_value);

    return 0;
}

How It Works

const int arr[] promises not to modify elements through arr. The cast on sizeof keeps size as int for this tutorial; with very large arrays prefer size_t.

📈 Practical Patterns

Same function still works when every value is negative.

Example 2 — When Every Element Is Negative

The “maximum” is the least negative value (here −1). Seeding from arr[0] is why this works without special cases.

c
#include <stdio.h>

int find_max(const int arr[], int size) {
    int max_val = arr[0];
    for (int i = 1; i < size; ++i) {
        if (arr[i] > max_val) {
            max_val = arr[i];
        }
    }
    return max_val;
}

int main(void) {
    int negatives[] = {-9, -3, -1, -7};
    int n = (int)(sizeof(negatives) / sizeof(negatives[0]));

    printf("Maximum (least negative): %d\n", find_max(negatives, n));

    return 0;
}

How It Works

Starting at -9, the scan promotes to -3, then -1. Never initialize with 0 when negatives are possible — 0 would wrongly win.

🧠 How the Algorithm Finds the Maximum

1

Validate length

Require size >= 1 (or handle empty arrays explicitly in production code).

Guard
2

Initialize

Set max = arr[0].

Seed
3

Scan

For i from 1 to size - 1, if arr[i] > max, set max = arr[i].

Compare
=

Return max

For the reference array, the answer is 42.

🔎 Worked Walkthrough — Reference Array

Trace the running maximum for {14, 7, 25, 31, 10, 42}.

iarr[i]Comparemax after
14seed14
177 > 14? no14
22525 > 14? yes25
33131 > 25? yes31
41010 > 31? no31
54242 > 31? yes42

Final answer: 42.

Use Cases

Where a running-maximum scan shows up beyond the interview prompt.

1. Loop Practice

Master index loops and comparisons.

Example: first array drill.

2. Peak Values

Highest score, temperature, or reading.

Example: sensor batches.

3. Complexity Talk

Lead into O(n) vs sorting follow-ups.

Example: interview Q&A.

4. Signed Data

Prove negatives do not break the scan.

Example: Example 2.

5. Pair with Min

Same loops; flip the comparison next.

Example: next tutorial.

6. Edge Awareness

Discuss empty and single-element arrays.

Example: production guards.

Pro Tip: say “seed from arr[0], then update on >” before writing the loop — and mention empty arrays if asked.

Advantages

Why the linear scan earns interview points.

  1. 1. Optimal for Max Alone

    You must look at every element at least once; one pass is enough.

  2. 2. Constant Extra Space

    Only a few scalars besides the input array.

  3. 3. Works with Negatives

    Seeding from arr[0] handles all-negative data.

  4. 4. Easy to Trace

    Whiteboard the running max cell by cell.

Pro Tip: do not sort first unless you need the full order — mention that if the interviewer probes alternatives.

Usage Tips

Small habits that keep max-finding code clean in interviews.

  1. 1. Seed from arr[0]

    Avoid magic constants like 0 or INT_MIN unless required.

  2. 2. Loop from Index 1

    You already accounted for index 0 as the seed.

  3. 3. Guard Empty Arrays

    State that size >= 1 or return an error path.

  4. 4. Use sizeof Carefully

    It works on real arrays, not decayed pointers in callees.

  5. 5. Quote O(n)

    Mention you do not need to sort for max alone.

Pro Tip: the walkthrough table is the fastest way to lock in updates before typing the loop.

Common Pitfalls

Mistakes that commonly break maximum-finding solutions in C.

  1. 1. Seeding with 0

    Fails when every element is negative.

    → Always seed from arr[0] (or a true lower bound).

  2. 2. Empty Array Access

    Reading arr[0] when size == 0 is undefined.

    → Validate length before the scan.

  3. 3. sizeof on a Pointer

    Inside a function that received a decayed pointer, sizeof is wrong.

    → Pass size explicitly from the caller.

  4. 4. Sorting First

    Wastes work when you only need the max.

    → Prefer the linear scan.

  5. 5. Using >= Incorrectly for “First” Index

    If you also need the index of the first max, prefer > so ties keep the earlier index.

    → Decide tie-breaking rules explicitly.

Edge Cases

Check these before calling the solution done.

Empty

size == 0

No maximum exists; guard before reading arr[0].

One element

size == 1

The loop body never runs; max_val stays correct as that single element.

Negatives

All negative

Max is the least negative; seeding from arr[0] handles it.

Duplicates

Repeated max

Returning the value is fine; index-of-max needs an explicit tie policy.

INT_MIN

Extreme ints

Seeding from data still works when INT_MIN appears in the array.

Floats

Floating-point

Same structure with double; be careful with NaN in numerical code.

🔄 Input / Output

Programs embed literals. To read from the user, call scanf in a loop after reading n, then pass the filled array and n to find_max.

SampleResult
{14, 7, 25, 31, 10, 42}42
{-9, -3, -1, -7}-1

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Trace a new array

  • Use {3, 9, 2, 9, 5}
  • Confirm max is 9

2. Return the index

  • Track both value and index
  • Decide first vs last on ties

3. Single-element case

  • Call with size == 1
  • Verify the loop never runs

4. Flip to minimum

  • Change > to <
  • Preview the next tutorial

Notes

  • Algorithm: running maximum from left to right.
  • Cost: O(n) time, O(1) extra space.
  • Edge: define behavior when n = 0.
  • Seed from data so all-negative arrays still work.

Quick Takeaway: seed max from arr[0], update on >, require a non-empty array, and quote O(n).

⏱️ Time and Space Complexity

ApproachTimeExtra space
Single scanO(n)O(1)
Wrap Up

🎉 Conclusion

Finding the maximum is a one-pass running comparison: seed from the first element, update whenever a larger value appears, and return the winner. Master both the mixed and all-negative samples so you can explain negatives and empty-array edges confidently.

Practice both examples above, then continue to finding the minimum — same loops with <.

max = arr[0], then update on arr[i] > max — with size >= 1.

💡 Best Practices

✅ Do

  • Seed the max from arr[0]
  • Require size >= 1 (or handle empty)
  • Pass size explicitly into helpers
  • Dry-run one mixed and one negative case
  • Quote O(n) time and O(1) space

❌ Don’t

  • Initialize max to 0 blindly
  • Read arr[0] when the array is empty
  • Use sizeof on a decayed pointer
  • Sort just to find the max
  • Ignore all-negative test cases

Key Takeaways

Knowledge Unlocked

Five things to remember about finding the max in C

Implement it the interview-friendly way.

5
Core concepts
> 02

Update

On larger

Scan
1 03

Pass

One loop

Code
04

Signs

Negatives OK

Edge
O 05

Cost

O(n)

Analysis

❓ Frequently Asked Questions

It picks an initial candidate from the data so every later comparison has something to beat. After one pass, max holds the largest value seen.
This tutorial assumes size >= 1. With zero elements there is no maximum; return an error code or avoid calling find_max until you validate size.
Yes. You still initialize max to the first element; comparisons use > so the largest value (closest to positive infinity among entries) wins—even if every entry is negative.
The scan returns one copy of the maximum value; duplicates do not change which number is printed.
Sorting costs more than O(n) for comparison sorts. A linear scan is enough for max alone.
One pass over n elements: O(n) time and O(1) auxiliary space aside from the input array.
For a real array (not a pointer), sizeof(array)/sizeof(array[0]) yields the element count so you do not hard-code the size by hand.
Same structure; flip the comparison to < and keep a running minimum instead.

Did you Know? 🔊

Finding the maximum in an unsorted array needs at least n − 1 comparisons in the worst case (standard adversary argument). A single left-to-right scan achieves O(n) time and O(1) extra space.

Continue to Minimum Value of an Array

Learn how to find the smallest element with the same linear-scan pattern in C.

Minimum of an Array tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful