Array Max & Min

Program to find maximum and minimum element in an array

BeginnerTopic: Array Programs
Back

C++ Array Max & Min Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <climits>
using namespace std;

int main() {
    int n;
    
    cout << "Enter number of elements: ";
    cin >> n;
    
    int arr[n];
    
    cout << "Enter " << n << " elements: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    
    int max = INT_MIN, min = INT_MAX;
    
    for (int i = 0; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    
    cout << "Maximum element: " << max << endl;
    cout << "Minimum element: " << min << endl;
    
    return 0;
}
Output
Enter number of elements: 5
Enter 5 elements: 10 5 20 15 8
Maximum element: 20
Minimum element: 5

Understanding Array Max & Min

This program finds the maximum (largest) and minimum (smallest) elements in an array. Finding max and min is one of the most fundamental array operations, used extensively in data analysis, sorting algorithms, and problem-solving. This program demonstrates array traversal, comparison logic, and initialization techniques.

---

1. What This Program Does

The program:

Takes an array of numbers as input
Finds the largest number (maximum) in the array
Finds the smallest number (minimum) in the array
Displays both results

Example:

Array: [10, 5, 20, 15, 8]
Maximum:

20

(largest value)

Minimum:

5

(smallest value)

Applications:

Data analysis (finding extremes)
Sorting algorithms
Statistical calculations
Competitive programming
Many real-world applications

---

2. Header Files Used

#include <iostream>

Provides cout for output and cin for input

#include <climits>

Provides constants for integer limits
Contains INT_MIN and INT_MAX
Essential for proper initialization

---

3. Understanding INT_MIN and INT_MAX

INT_MIN:

Smallest possible integer value
Typically: -2,147,483,648 (on 32-bit systems)
Any integer is greater than or equal to INT_MIN

INT_MAX:

Largest possible integer value
Typically: 2,147,483,647 (on 32-bit systems)
Any integer is less than or equal to INT_MAX

Why use these for initialization?

We want max to be smaller than any possible array element
We want min to be larger than any possible array element
This ensures first comparison always updates the value

---

4. Declaring Variables

int n;

int arr[n];

int max = INT_MIN, min = INT_MAX;

Variable `n`:

Stores the number of elements in the array
Used to create array and control loops

Variable `arr[n]`:

Array to store the input numbers
Size is determined by n

Variable `max`:

Stores the maximum element found so far

-

Initialized to INT_MIN

ensures any number will be larger

Variable `min`:

Stores the minimum element found so far

-

Initialized to INT_MAX

ensures any number will be smaller

Why these initial values?

First array element will always be:
Greater than INT_MIN → updates max ✅
Less than INT_MAX → updates min ✅

---

5. Taking Input From User

`cout << "Enter number of elements: ";`

cin >> n;

`cout << "Enter " << n << " elements: ";`

for (int i = 0; i < n; i++)

cin >> arr[i];

Step 1: Get array size

User enters how many numbers they want to input
Example:

5

Step 2: Get array elements

Loop reads n numbers
Stores them in array: arr[0], arr[1], ..., arr[n-1]

Example:

User enters:

10 5 20 15 8

arr[0] = 10, arr[1] = 5, arr[2] = 20, arr[3] = 15, arr[4] = 8

---

6. Finding Maximum Element

for (int i = 0; i < n; i++)

if (arr[i] > max)

max = arr[i];

How it works:

Initial:

max = INT_MIN (very small number)

Iteration 1 (i = 0):

Check: arr[0] (10) > max (INT_MIN)

true

Update: max = 10

Iteration 2 (i = 1):

Check: arr[1] (5) > max (10)

false

max remains 10

Iteration 3 (i = 2):

Check: arr[2] (20) > max (10)

true

Update: max = 20

Iteration 4 (i = 3):

Check: arr[3] (15) > max (20)

false

max remains 20

Iteration 5 (i = 4):

Check: arr[4] (8) > max (20)

false

max remains 20

Result:

max = 20

---

7. Finding Minimum Element

for (int i = 0; i < n; i++)

if (arr[i] < min)

min = arr[i];

How it works:

Initial:

min = INT_MAX (very large number)

Iteration 1 (i = 0):

Check: arr[0] (10) < min (INT_MAX)

true

Update: min = 10

Iteration 2 (i = 1):

Check: arr[1] (5) < min (10)

true

Update: min = 5

Iteration 3 (i = 2):

Check: arr[2] (20) < min (5)

false

min remains 5

Iteration 4 (i = 3):

Check: arr[3] (15) < min (5)

false

min remains 5

Iteration 5 (i = 4):

Check: arr[4] (8) < min (5)

false

min remains 5

Result:

min = 5

---

8. Why Initialize to INT_MIN and INT_MAX?

Alternative (wrong) approach:

int max = 0, min = 0;  // WRONG!

Problem:

If all numbers are negative: max would stay 0 (wrong!)
If all numbers are positive: min would stay 0 (wrong!)

Our approach:

max = INT_MIN → any number will be larger
min = INT_MAX → any number will be smaller
Works correctly for any input (positive, negative, or mixed)

---

9. Optimized Version (Single Loop)

We can find both max and min in a single loop:

for (int i = 0; i < n; i++) {
    if (arr[i] > max) max = arr[i];
    if (arr[i] < min) min = arr[i];
}

Advantages:

Only one loop instead of two
More efficient (fewer iterations)
Same time complexity, but faster in practice

Our program uses this optimized approach!

---

10. Complete Example Walkthrough

Input:

Array = [10, 5, 20, 15, 8]

Initialization:

max = INT_MIN (very small)
min = INT_MAX (very large)

Iteration 1 (arr[0] = 10):

10 > INT_MIN

true

max = 10

10 < INT_MAX

true

min = 10

Iteration 2 (arr[1] = 5):

5 > 10

false

→ max stays 10

5 < 10

true

min = 5

Iteration 3 (arr[2] = 20):

20 > 10

true

max = 20

20 < 5

false

→ min stays 5

Iteration 4 (arr[3] = 15):

15 > 20

false

→ max stays 20

15 < 5

false

→ min stays 5

Iteration 5 (arr[4] = 8):

8 > 20

false

→ max stays 20

8 < 5

false

→ min stays 5

Final Results:

max = 20
min = 5

---

11. Displaying the Results

`cout << "Maximum element: " << max << endl;`
`cout << "Minimum element: " << min << endl;`

Output:

-

Maximum element: 20

-

Minimum element: 5

---

12. Edge Cases

Case 1: All elements are same

Array: [5, 5, 5, 5]
max = 5, min = 5 ✅

Case 2: All negative numbers

Array: [-10, -5, -20]
max = -5, min = -20 ✅
INT_MIN initialization ensures this works

Case 3: Single element

Array: [42]
max = 42, min = 42 ✅

Case 4: Sorted array (ascending)

Array: [1, 2, 3, 4, 5]
max = 5 (last element), min = 1 (first element)

Case 5: Sorted array (descending)

Array: [5, 4, 3, 2, 1]
max = 5 (first element), min = 1 (last element)

---

13. Time Complexity

Time Complexity: O(n)

We iterate through the array once
n comparisons for max, n comparisons for min
Total: 2n comparisons = O(n)

Space Complexity: O(n)

Array storage: O(n)
Variables: O(1)
Total: O(n)

This is optimal!

We must check every element at least once.

---

14. Alternative: Using First Element

Alternative initialization:

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

Advantages:

No need for INT_MIN/INT_MAX
Start loop from index 1 (slightly faster)

Disadvantages:

Requires array to have at least one element
Need to handle empty array separately

---

Summary

Find max: Initialize to INT_MIN, update when finding larger value
Find min: Initialize to INT_MAX, update when finding smaller value
Single loop can find both efficiently
Time complexity: O(n) - optimal
Works correctly for any input (positive, negative, mixed)

This program teaches:

Array traversal and iteration
Comparison logic
Proper initialization techniques
Finding extremes in data
Efficient algorithm design

Understanding max/min finding helps in:

Data analysis and statistics
Sorting algorithm design
Competitive programming
Many real-world applications

Finding maximum and minimum are fundamental operations that appear in almost every data processing application. This program demonstrates an efficient and correct way to implement them.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Array Max & Min

This C++ program is part of the "Array Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents