How to Find Maximum Value in Array in C++

Jinku Hu Feb 12, 2024
  1. Find Maximum Value in an Array in C++ Using the Iterative Approach
  2. Find Maximum Value in an Array in C++ Using STL Algorithm max_element
  3. Find Maximum Value in an Array in C++ Using the std::minmax_element Algorithm
  4. Find Maximum Value in an Array in C++ Using the Range-Based for Loop
  5. Find Maximum Value in an Array in C++ Using the Recursive Approach
  6. Conclusion
How to Find Maximum Value in Array in C++

In C++ programming, a common task often encountered is the need to find the maximum value within an array. Addressing this requirement opens the door to various strategies, each offering unique approaches and advantages.

In this article, we will explore several methods, from traditional iterative techniques to leveraging the Standard Template Library (STL) algorithms and from the simplicity of range-based for loops to the recursive strategies.

Find Maximum Value in an Array in C++ Using the Iterative Approach

One of the straightforward methods to finding the maximum value within an array in C++ is through the iterative approach. This method involves traversing through each element of the array and updating a variable to hold the maximum value encountered so far.

Steps for the Iterative Approach

  • Start by initializing a variable to hold the maximum value. Set it to the value of the first element in the array since there is no comparison yet.
  • Use a loop to iterate through the array, starting from the second element. For each element, compare it with the current maximum value.
  • If the current element is greater than the current maximum value, update the maximum value with the value of the current element.
  • Continue the iteration until all elements are checked. The final value of the maximum variable will be the maximum value in the array.

Now, let’s delve into a complete working example showcasing the Iterative Approach in C++.

#include <iostream>

// Function to find the maximum value using the Iterative Approach
template <typename T>
T FindMax(T *arr, size_t n) {
  T maxVal = arr[0];  // Step 1

  for (size_t i = 1; i < n; ++i) {  // Step 2
    if (arr[i] > maxVal) {          // Step 3
      maxVal = arr[i];              // Step 3
    }
  }

  return maxVal;  // Step 4
}

int main() {
  int arr[] = {4, 7, 2, 8, 5};  // Example array
  size_t size = sizeof(arr) / sizeof(arr[0]);

  // Call the function to find the maximum value
  int maxVal = FindMax(arr, size);

  // Display the result
  std::cout << "Maximum value: " << maxVal << std::endl;

  return 0;
}

Here, we begin by initializing a variable maxVal with the value of the first element in the array (arr[0]). This serves as the starting point for the comparison process.

We have a for loop (Step 2) that iterates through the array, starting from the second element (i = 1). Within the loop, an if statement (Step 3) checks whether the current array element (arr[i]) is greater than the current maximum value (maxVal).

If this condition is true, it means that a new maximum value has been found, and maxVal is updated to hold the value of the current element. This ensures that maxVal always represents the maximum value encountered during the iteration.

The loop continues until all elements in the array have been examined. Once the loop concludes, the function returns the final maximum value stored in maxVal (Step 4).

In the main function, an example integer array (arr[] = {4, 7, 2, 8, 5}) is declared. The size of the array (size) is calculated using the sizeof operator.

Subsequently, the FindMax function is called with the array and its size as arguments, and the result is stored in the variable maxVal. Finally, the maximum value is displayed using std::cout.

Code Output:

Find Maximum Value in an Array in C++ Using the Iterative Approach

This result demonstrates the successful application of the Iterative Approach to find the maximum value in the given array.

Find Maximum Value in an Array in C++ Using STL Algorithm max_element

In C++, the Standard Template Library (STL) provides powerful algorithms that simplify common tasks. One such task is finding the maximum value in an array.

Let’s see how we can use the std::max_element algorithm, a part of the STL, to efficiently locate the maximum value within an array.

Steps for Using the std::max_element Function

  • To use the std::max_element algorithm, include the <algorithm> header in your code.
  • Invoke the std::max_element function, providing it with two iterators that denote the range within which to search for the maximum value.
  • The function returns an iterator pointing to the maximum value within the specified range. Dereference this iterator to obtain the actual maximum value.

Now, let’s delve into a complete working example showcasing the use of the std::max_element algorithm in C++.

#include <algorithm>
#include <iostream>

// Function to find the maximum value using the std::max_element algorithm
template <typename T>
T FindMaxUsingSTL(T *arr, size_t n) {
  // Use std::max_element to find the iterator pointing to the maximum element
  auto maxElementIterator = std::max_element(arr, arr + n);

  // Dereference the iterator to get the actual maximum value
  T maxVal = *maxElementIterator;

  return maxVal;
}

int main() {
  int arr[] = {4, 7, 2, 8, 5};  // Example array
  size_t size = sizeof(arr) / sizeof(arr[0]);

  // Call the function to find the maximum value using std::max_element
  int maxVal = FindMaxUsingSTL(arr, size);

  // Display the result
  std::cout << "Maximum value using std::max_element: " << maxVal << std::endl;

  return 0;
}

As you can see within the FindMaxUsingSTL function, the std::max_element algorithm is utilized to find the iterator pointing to the maximum element in the specified range, which is defined by the iterators arr (beginning of the array) and arr + n (one past the end of the array). The iterator obtained from this operation is stored in the maxElementIterator variable.

Subsequently, the iterator is dereferenced to obtain the actual maximum value, and this value is assigned to the variable maxVal. Finally, the function returns the calculated maximum value.

In the main function, an example integer array (arr[] = {4, 7, 2, 8, 5}) is declared. The size of the array (size) is calculated using the sizeof operator and dividing by the size of an individual array element.

The FindMaxUsingSTL function is then called with the array and its size as arguments, and the result is stored in the variable maxVal. In order to display the result, the maximum value is outputted to the console using std::cout.

Code Output:

Find Maximum Value in an Array in C++ Using std::max_element

This demonstrates the successful utilization of the std::max_element algorithm to find the maximum value in the given array.

Find Maximum Value in an Array in C++ Using the std::minmax_element Algorithm

Another useful algorithm provided by the Standard Template Library (STL) for finding the maximum value in an array is std::minmax_element. This algorithm not only locates the maximum value but also identifies the minimum value within the specified range.

Take a look at the steps involved in using std::minmax_element.

Steps for Using the std::minmax_element Function

  • To use the std::minmax_element algorithm, include the <algorithm> header in your code.
  • Invoke the std::minmax_element function, providing it with two iterators that denote the range within which to search for the minimum and maximum values.
  • The function returns a pair of iterators – the first pointing to the minimum element and the second to the maximum element. Dereference the second iterator to obtain the actual maximum value.

Now, let’s delve into a complete working example showcasing the use of the std::minmax_element algorithm in C++.

#include <algorithm>
#include <iostream>

// Function to find the maximum value using the std::minmax_element algorithm
template <typename T>
T FindMaxUsingMinmax(T *arr, size_t n) {
  // Use std::minmax_element to find the iterators pointing to the min and max
  // elements
  auto minMaxPair = std::minmax_element(arr, arr + n);

  // Dereference the second iterator to get the actual maximum value
  T maxVal = *minMaxPair.second;

  return maxVal;
}

int main() {
  int arr[] = {4, 7, 2, 8, 5};  // Example array
  size_t size = sizeof(arr) / sizeof(arr[0]);

  // Call the function to find the maximum value using std::minmax_element
  int maxVal = FindMaxUsingMinmax(arr, size);

  // Display the result
  std::cout << "Maximum value using std::minmax_element: " << maxVal
            << std::endl;

  return 0;
}

Within the FindMaxUsingMinmax function, the std::minmax_element algorithm is utilized to find a pair of iterators pointing to the minimum and maximum elements in the specified range. The range is defined by the iterators arr (representing the beginning of the array) and arr + n (representing one position past the end of the array).

The resulting pair of iterators is stored in the minMaxPair variable.

Following this, the second iterator in the pair (pointing to the maximum element) is dereferenced, and the actual maximum value is obtained. This maximum value is assigned to the variable maxVal, which is then returned by the function.

In the main function, the same example integer array (arr[] = {4, 7, 2, 8, 5}) is declared. The size of the array (size) is calculated using the sizeof operator and dividing by the size of an individual array element.

The FindMaxUsingMinmax function is called with the array and its size as arguments, and the result is stored in the variable maxVal. In order to display the result, the maximum value is outputted to the console using std::cout.

Code Output:

Find Maximum Value in an Array in C++ Using std::minmax_element

This confirms the successful application of the std::minmax_element algorithm to find the maximum value in the given array.

Find Maximum Value in an Array in C++ Using the Range-Based for Loop

Another concise and modern approach to finding the maximum value in an array involves the use of a range-based for loop. This method simplifies the code and enhances readability by directly iterating over the elements of the array.

Here are the steps involved in using a range-based for loop for this purpose.

Steps for Using the Range-Based for Loop

  • Start by declaring a variable to hold the maximum value. Initialize it with a value that ensures the first comparison will result in an update.
  • Use a range-based for loop to iterate through each element of the array directly. For each element, check if it is greater than the current maximum value.
  • If the current element is greater than the current maximum value, update the maximum value with the value of the current element.

Now, let’s delve into a complete working example showcasing the use of a range-based for loop in C++ to find the maximum value in an array.

#include <iostream>

// Function to find the maximum value using Range-based For Loop
template <typename T>
T FindMaxUsingRangeForLoop(T *arr, size_t n) {
  T maxVal = arr[0];  // Step 1

  for (size_t i = 0; i < n; ++i) {  // Step 2
    if (arr[i] > maxVal) {          // Step 3
      maxVal = arr[i];              // Step 3
    }
  }

  return maxVal;
}

int main() {
  int arr[] = {4, 7, 2, 8, 5};  // Example array
  size_t size = sizeof(arr) / sizeof(arr[0]);

  // Call the function to find the maximum value using Range-based For Loop
  int maxVal = FindMaxUsingRangeForLoop(arr, size);

  // Display the result
  std::cout << "Maximum value using Range-based For Loop: " << maxVal
            << std::endl;

  return 0;
}

In the FindMaxUsingRangeForLoop function, we begin by declaring a variable maxVal and initializing it with the value of the first element in the array (arr[0]). This sets the starting point for the comparison process (Step 1).

Next, a traditional for loop is employed to iterate through each element of the array (arr). The loop condition (i < n) ensures that the iteration covers all elements in the array.

Within the loop, an if statement checks if the current array element (arr[i]) is greater than the current maximum value (maxVal). If this condition is true, it indicates that a new maximum value has been found, and maxVal is updated to hold the value of the current element (Step 3).

The loop continues until all elements in the array have been examined. Once the loop concludes, the function returns the final maximum value stored in maxVal.

In the main function, an example integer array (arr[] = {4, 7, 2, 8, 5}) is declared. The size of the array (size) is calculated using the sizeof operator and dividing by the size of an individual array element.

The FindMaxUsingRangeForLoop function is then called with the array and its size as arguments, and the result is stored in the variable maxVal.

Code Output:

Find Maximum Value in an Array in C++ Using Range-based For Loop

This confirms the successful application of the range-based for loop to find the maximum value in the given array.

Find Maximum Value in an Array in C++ Using the Recursive Approach

A recursive approach to finding the maximum value in an array provides an alternative method, leveraging the concept of dividing the problem into smaller subproblems.

Below are the steps involved in implementing a recursive approach to find the maximum value in an array.

Steps for Using the Recursive Approach

  • Identify a base case that indicates when the recursion should stop. In this case, the base case is when there is only one element in the array.
  • Break down the problem into smaller subproblems. In this context, split the array into two halves.
  • Recursively call the function on each subproblem.
  • Combine the results from the subproblems to obtain the overall solution.

Now, let’s delve into a complete working example showcasing the use of a recursive approach in C++ to find the maximum value in an array.

#include <iostream>

// Function to find the maximum value using the Recursive Approach
template <typename T>
T FindMaxRecursive(T *arr, size_t start, size_t end) {
  // Base Case: If there is only one element
  if (start == end) {
    return arr[start];
  }

  // Divide the problem: Find a mid-point
  size_t mid = (start + end) / 2;

  // Recursive Calls on two halves
  T maxLeft = FindMaxRecursive(arr, start, mid);
  T maxRight = FindMaxRecursive(arr, mid + 1, end);

  // Combine Results: Return the maximum of the two halves
  return (maxLeft > maxRight) ? maxLeft : maxRight;
}

int main() {
  int arr[] = {4, 7, 2, 8, 5};  // Example array
  size_t size = sizeof(arr) / sizeof(arr[0]);

  // Call the function to find the maximum value using Recursive Approach
  int maxVal = FindMaxRecursive(arr, 0, size - 1);

  // Display the result
  std::cout << "Maximum value using Recursive Approach: " << maxVal
            << std::endl;

  return 0;
}

In the above example, we begin by addressing the base case: if the starting index (start) is equal to the ending index (end), it means there is only one element in the specified range. In such a case, the function directly returns the value of that single element, indicating the maximum value in that particular subproblem.

For cases where there is more than one element, the function proceeds to divide the problem into smaller subproblems.

It calculates the mid-point index (mid) by averaging the starting and ending indices. This mid-point becomes the dividing point for the two halves of the array.

The function then makes recursive calls on the two halves separately. The left half spans from the starting index to the mid-point, and the right half spans from the mid-point plus one to the ending index.

These recursive calls delve deeper into each subproblem, eventually reaching the base case.

Once the base cases are resolved and the recursive calls are complete, the function combines the results from the two halves.

It compares the maximum values obtained from the left and right halves and returns the greater of the two. This process effectively finds the maximum value across the entire array.

In the main function, an example integer array is declared, and the size of the array (size) is calculated using the sizeof operator and dividing by the size of an individual array element. The FindMaxRecursive function is then called with the array, the initial and final indices (0 and size - 1), and the result is stored in the variable maxVal.

Code Output:

Find Maximum Value in an Array in C++ Using Recursive Approach

This confirms the successful application of the recursive approach to find the maximum value in the given array.

Conclusion

In conclusion, this article has explored various methods to find the maximum value in an array in C++. We covered traditional approaches like the iterative method, STL algorithms like std::max_element and std::minmax_element, the range-based for loop, and a recursive approach.

Each method offers its unique advantages, catering to different preferences and scenarios. Whether opting for efficiency, simplicity, or a balance between the two, you can choose the method that best fits your specific requirements.

The diverse set of techniques presented here underscores the flexibility and richness of C++ as a programming language, providing you with a toolkit of strategies to tackle the common task of finding the maximum value in an array.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ Array