Function Assignment 18 — Find the Maximum Element in an Array Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Maximum Element in an Array Using a Function

📑 On this page:
  • The running-maximum pattern
  • Designing the findMax function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to pass an array to a function — and why the size must be passed separately
  • How the "running maximum" pattern works
  • Why initializing max to arr[0] is safer than initializing to 0
  • How to handle empty arrays and arrays of all-negative numbers
  • How this pattern extends to finding the minimum, the second maximum, and beyond

The running-maximum pattern

Finding the maximum of an array is one of the simplest algorithms in programming, and it's a perfect first exercise for arrays in functions. The idea: keep a variable that holds "the largest 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 larger. At the end, the variable holds the overall maximum.

This pattern — the "running maximum" — is a fundamental idiom that shows up everywhere. Finding the maximum, the minimum, the longest streak, the highest score, the peak value — they're all variations on the same theme. Once you've internalized it, you'll recognize it in dozens of other problems. It's the kind of small, reliable primitive that compounds into larger algorithms.

There are a few subtleties worth getting right from the start. First, initialize max to the first element, not to 0. If the array is all negative, initializing to 0 would give a wrong answer (0 would appear to be the maximum). Second, handle the empty-array case explicitly — if n == 0, there's no maximum to find. Third, use const on the array parameter, since you're only reading, not modifying. Getting these right makes the function robust and correct.

Another consideration: the array decays to a pointer when passed to a function, so the function has no way to know its length unless the caller tells it. That's why the signature is findMax(int arr[], int n) — the n parameter carries the length, which the function can't derive from the pointer alone. This is a fundamental C convention, and getting used to it is part of becoming comfortable with arrays.

💡 In one line: set max = arr[0], then for each i from 1 to n-1, if arr[i] > max, set max = arr[i]. After the loop, max is the largest element.

A row of numbers with one highlighted as the maximum, showing the running-max comparison.

Designing the findMax function

The signature is standard for array-passing functions:

Part Choice Why
Function namefindMaxDescriptive. Alternative: arrayMax, getMax.
Array parameterconst int arr[]Arrays decay to pointers, so this is really const int *arr. The const means "we won't modify the array."
Size parameterint nRequired because the array decays to a pointer — the function can't determine length from the pointer. This is the standard C convention.
Return typeintReturns the largest element. If the array could contain long long values, the return type would be long long too.

The prototype:

int findMax(const int arr[], int n);
                                

And the definition:

int findMax(const int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}
                                

Six lines of logic. The loop starts at index 1 because index 0 is already the initial maximum — there's no need to compare arr[0] to itself. Each iteration does one comparison and possibly one assignment. After the loop, max holds the largest value.

An alternative using a conditional expression (ternary) makes it slightly shorter:

int findMax(const int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        max = (arr[i] > max) ? arr[i] : max;
    }
    return max;
}
                                

Functionally identical. Some people find the explicit if clearer, some prefer the ternary. For this small case, either is fine — the compiler generates the same code. Use whichever your team finds more readable.

And here's the function written with a pointer that walks the array, which is a slightly more idiomatic C style:

int findMax(const int *arr, int n) {
    int max = *arr;
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) max = arr[i];
    }
    return max;
}
                                

The declaration int arr[] and int *arr are identical in a function parameter list — the array syntax is just syntactic sugar for the pointer. Use whichever you find more readable; they compile to the same code.

🎯 Key idea: initialize max to arr[0], not 0. If the array is all negative, initializing to 0 would make the function return 0 — which isn't even in the array. Initializing to the first element avoids this trap and is the standard pattern.

Complete C Program

Program: read an array, find the maximum

#include <stdio.h>

/* Function prototype */
int findMax(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("Maximum: %d\n", findMax(arr, n));

    return 0;
}

/* Find the largest element */
int findMax(const int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}
                                    

And a version that also finds the minimum, so you can see the parallel structure:

Variant: max and min together

#include <stdio.h>

int findMax(const int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i];
    return max;
}

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;
}

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]);

    printf("Maximum: %d\n", findMax(arr, n));
    printf("Minimum: %d\n", findMin(arr, n));
    return 0;
}
                                    

The two functions are structurally identical — the only difference is the comparison direction (> for max, < for min). This parallel structure is a good sign that you've found the right abstraction: the same algorithm, parameterized by a single comparison.

And a version that prints the index of the maximum — useful when you care about where the max occurs, not just what it is:

Variant: return the index of the maximum

#include <stdio.h>

int findMaxIndex(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 = findMaxIndex(arr, n);
    printf("Max value: %d at index %d\n", arr[idx], idx);
    return 0;
}
                                

This version tracks an index instead of a value. Each comparison is arr[i] > arr[idx] — comparing the value at index i to the value at index idx — and if it's larger, we update idx. After the loop, arr[idx] is the maximum, and idx is where it lives. This is useful when you need to know not just "what's the max" but "where is it" — for example, when the array contains records and you want to retrieve the full record of the maximum.

Program Output

A typical run:

How many elements? 5
Enter 5 integers: 3 7 2 9 4
Maximum: 9
                                

With all negative numbers — the case where initializing to 0 would be wrong:

How many elements? 4
Enter 4 integers: -5 -2 -8 -1
Maximum: -1
                                

Notice the output is -1 — the largest of the four negative numbers. If we'd initialized max to 0, the function would have returned 0, which isn't even in the array. This is why initializing to arr[0] is essential.

With a single element:

How many elements? 1
Enter 1 integers: 42
Maximum: 42
                                

The loop for (i = 1; i < 1; i++) doesn't execute at all, and the function returns arr[0], which is 42. Correct.

With an array where the maximum is at the end:

How many elements? 5
Enter 5 integers: 1 2 3 4 5
Maximum: 5
                                

The max variable gets updated on every iteration — 1 → 2 → 3 → 4 → 5. This is the "worst case" for the max-tracking variable, but the loop count is the same. The function is correct either way.

With an array where the maximum is at the start:

How many elements? 5
Enter 5 integers: 5 4 3 2 1
Maximum: 5
                                

The max variable stays at 5 throughout — no updates needed. The loop still runs all four iterations, but each comparison fails. This is a good sanity check: the algorithm is correct regardless of where the max is, or how the other elements are arranged.

Step-by-Step Explanation

Let's trace the algorithm on a concrete example and look at why each part is designed the way it is.

1. Initialization: max = arr[0]

arr[0] is the first element. Initializing max to it means "the largest element seen so far is the first one." This is trivially true at the start — we haven't seen anything else yet. Some programmers prefer initializing to INT_MIN (from <limits.h>) to avoid the assumption that the array isn't empty, but the first-element approach is simpler and works for any non-empty array. For empty arrays, we need a check before calling (which our program does via the n <= 0 check).

2. The loop starts at index 1

We've already considered arr[0], so we start the scan at arr[1]. Starting at index 0 would just compare arr[0] > arr[0], which is always false — wasted work. Starting at 1 is the correct optimization.

3. The comparison and update

if (arr[i] > max) max = arr[i]; — the heart of the algorithm. For each element, check if it's larger than the current maximum. If so, it becomes the new maximum. If not, skip it. Note the strict inequality: if arr[i] == max, we don't update, which is fine — the maximum is the same value, so it doesn't matter which index we point at.

4. Tracing findMax({3, 7, 2, 9, 4}, 5)

  1. max = arr[0] = 3.
  2. i = 1: arr[1] = 7. 7 > 3? Yes. max = 7.
  3. i = 2: arr[2] = 2. 2 > 7? No. max stays 7.
  4. i = 3: arr[3] = 9. 9 > 7? Yes. max = 9.
  5. i = 4: arr[4] = 4. 4 > 9? No. max stays 9.
  6. Loop ends. Return 9. ✓

Four comparisons, one update. For a 5-element array, that's the minimum work needed to establish the maximum (you can't prove a value is the max without comparing it to all the others).

5. Why the array size must be passed explicitly

In C, when you pass an array to a function, the array decays to a pointer to its first element. Inside the function, arr is just int * — a pointer — and there's no way to recover the original size from it. sizeof(arr) inside the function would return sizeof(int *) (usually 8 bytes), not the size of the array. That's why the standard pattern is to pass the size as a separate parameter. It's a small inconvenience, but it's the way C works, and getting used to it is essential.

6. Why const matters

const int arr[] means the function promises not to modify the array's elements. The compiler enforces this — if you accidentally write arr[i] = 0; somewhere inside the function, you'll get a compile-time error. This is a safety net, and it also documents the function's intent to anyone reading the signature. For a pure query function like findMax, const is the right choice.

7. The all-negative case

If you initialized max = 0 instead of max = arr[0], then for an all-negative array (like {-5, -2, -8, -1}), the comparison arr[i] > 0 would always be false, and max would stay 0. The function would return 0, which isn't even in the array. Initializing to arr[0] avoids this entirely — max starts as a real element, and the loop correctly tracks the largest one.

8. Handling the empty-array case

If n == 0, our function would try to access arr[0] — reading from an empty array is undefined behavior (typically a segfault, or reading garbage data). To handle this correctly, either check for n == 0 in the function and return some sentinel value, or validate the input in main before calling. Our program does the latter: it rejects n <= 0 at input time. This keeps the function simple and the caller responsible for preconditions — a common division of labor in C.

9. Complexity

The loop runs n - 1 iterations, each doing one comparison and possibly one assignment. That's O(n) time — the minimum possible, since you have to look at every element to be sure it's not larger. Space is O(1) beyond the input array. So the function is optimal in both dimensions. No sorting, no recursion, no clever tricks — just a single linear scan, which is what this problem calls for.

10. Variations and extensions

Once you have this pattern, many related problems follow easily:

  • Minimum: identical, but with < instead of >.
  • Index of the maximum: track the index instead of the value (as shown in the variant).
  • Second maximum: keep two variables, max and secondMax, and update both in each iteration.
  • Maximum and minimum together: track both in one pass (as shown in the variant).
  • Peak element: for an array where consecutive elements differ, find a local maximum using binary search.

All of these build on the same core idea: iterate once, maintain running state, update on each element. That's the pattern — and once it's in your toolkit, the specific problem becomes a detail.

🔍 Try this: modify the program to print the index of the maximum as well as the value. Then modify it to also print the sum of all elements. Then the average. Each addition is a small change to the same loop or a second loop over the same array. This is how real programs grow — one feature at a time, layered on the same core logic.

Frequently Asked Questions

1. Why do I have to pass the array size separately?

Because C arrays decay to pointers when passed to functions — the function has no way to know how many elements the original array had. In the caller, sizeof(arr) gives the array's total byte size; inside a function that took arr as a parameter, sizeof(arr) gives the size of the pointer (8 bytes on most systems). So the size must be passed as a separate parameter, and the standard C convention is to do exactly that. It's a small annoyance, but it's how C works, and getting used to it is essential for working with arrays.

2. 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. Two approaches handle this: (a) check for n == 0 inside the function and return a sentinel value (like INT_MIN, but that could be a real maximum, so it's ambiguous), or (b) validate in the caller before calling (which our program does). Option (b) is cleaner because the function has a simple contract ("n ≥ 1"), and the caller handles the edge case. In practice, most code that operates on arrays assumes non-empty and validates at the boundary — that's a common and reasonable convention.

3. Why not use INT_MIN as the initial value?

You can — it works correctly. Initializing to INT_MIN (the smallest possible int) is safe because any array element is guaranteed to be ≥ INT_MIN, so the first comparison will update max (unless the first element is exactly INT_MIN, in which case it stays there — but that's the correct answer anyway). Both approaches are correct. Initializing to arr[0] is slightly more intuitive: "the max is the first element, until proven otherwise." Initializing to INT_MIN is slightly more defensive: "the max is the smallest possible, and we'll find the real one." Use whichever reads better to you.

4. What if there are duplicate maxima?

For finding the maximum value, duplicates don't matter — the value is the same. If you're tracking the index, our function returns the index of the first occurrence of the maximum (because of the strict > comparison — subsequent equal values don't update). To get the last occurrence, use >= instead. Different applications want different behavior — clarify which one you need before writing the code.

5. Can this work on arrays of other types?

Yes — the pattern is identical for float, double, long long, or any comparable type. Just change the parameter and return types: double findMax(const double arr[], int n). For strings, you'd compare with strcmp instead of >. For structs, you'd need a custom comparison function or use qsort with one. The core algorithm — running maximum — is type-agnostic; only the comparison changes.

6. How does this compare to sorting?

Sorting is O(n log n) — much slower than the O(n) scan. If all you need is the maximum, sorting is overkill. You'd only sort if you need the elements in order for some other reason. A common misconception is that sorting is the "right" way to find the max — it isn't. The single-pass scan is simpler, faster, and doesn't modify the input. This is a good example of choosing the right algorithm for the problem, rather than reaching for a general-purpose tool.

💡 Tip: Once this works, try finding the second maximum — the largest value strictly less than the maximum. It requires two tracking variables and careful handling of duplicates. Then try finding the mode (most frequent value) — a different but related problem. Both are common interview questions, and both build on the running-max pattern you've just learned. The path from "find the max" to "find the second max" to "find the k-th largest" is a natural progression that teaches you more sophisticated array techniques along the way.

📖 Related Tutorials

  • Introduction to Functions in C
  • One Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Concatenate Two Strings Using a Function
  • Next: Find the Minimum Element in an Array Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 17. Concatenate Two Strings Using a Function   ||   Next Topic: -->> 19. Find the Minimum Element in an Array Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.