How to Find Max Value in Array C++
In C++ language, which is also known as one of the most foundational languages when it comes to programming and has been in the world for many years, whenever we work with a list of numbers, we have to make sure or usually want to find the biggest number in the list. This operation or method can be useful for a lot of tasks in our day-to-day life, like when we want to create a bigger picture or work with pictures, or we have to sort a list containing numbers or when we are doing some kind of math stuff. These are cases where this method comes in handy. In this tutorial, we are basically going to see the different methods that we are going to use to make this work and find the maximum value in an array. Later, we will also examine the implementation of these methods to understand them better.
1. Linear Search Method
When we talk about the easiest and most simple approach, the one naïve approach that comes to our mind is the one in which we one by one go and traverse the whole array or list and take another variable in which we will be going to store the largest number that we might have seen while traversing and at the end of the traversal, meaning when we have finished traversing, we just have to return the variable storing the largest number. This approach is also known as the brute force approach and also has a bigger time complexity.
Approach
In this, we will be seeing the approach of how to solve it: -
- We have to start with the traversal of the array, and we have created a variable “max” and initialised it with the first element of the array, implying that it will contain this value until proven otherwise.
- Then, we have to start traversing the array and compare the current value with the value stored in the max variable; if the current value is greater than the max value, then we have to update the value stored in the max variable, and in the other case, we have to just move forward in the array.
- After iterating through the whole array and repeating the above steps, our variable max will hold the maximum value, which we can return at the end of the program.
Implementation
#include <iostream>
// Function to find the maximum value in an array
int findMax(int arr[], int length) {
if (length == 0) {
// If the array is empty, return an error value
std::cerr << "Caution: Cannot proceed further; the array is empty !" << std::endl;
return -1;
}
int maxVal = arr[0]; // Assume first element as maximum
for (int i = 1; i < length; ++i) {
if (arr[i] > maxVal) {
maxVal = arr[i]; // Update max if current element is greater
}
}
return maxVal;
}
int main() {
// Example array
int arr[] = {33, 07, 21, 8, 11, 99, 34, 61, 65};
int length = sizeof(arr) / sizeof(arr[0]); // Calculate array size
// Call the findMax function to get the maximum value
int maxVal = findMax(arr, length);
// Check if the findMax function returned an error
if (maxVal != -1) {
std::cout << "Hello user, the largest element present in the array is: " << maxVal << std::endl;
}
return 0;
}
Output:
![How to Find Max Value in Array C++/>
<!-- /wp:html -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-find-max-value-in-array-cpp1.png)
Earlier, we have talked about the naïve approach or the most basic approach, where we can just solve the problem or the basic approach that comes to our mind when we see the problem, but in C++ language, we also have some built-in libraries and tools which will help us in solving the problems more efficiently. One of the tools is called the “std::max_element", which we can easily find out in the algorithm part and will basically help us find out the biggest number in a list or array.
Approach
- The very first thing that we have to do is to import the essential headers without whom our program might fail, and these are <vector>, <algorithm> and <iostream>.
- Ask the user to enter the size of the array and check whether it is valid, meaning if its size is greater than 0. If it's a valid array, then ask the user to give in some elements of the array as well.
- Now, we have to use the "std::max_element” function to find out the maximum element in the array.
- The above function will basically return an index value or iterator pointing to the value.
- We have to next check whether the value on the iterator is valid. If it's valid, we have to simply extract the value from this iterator and return it as the max value. If it's not, we can just return either—1 or a print statement saying we couldn't find the value.
- For the base case, if the array is empty, we can also print a message stating that it is empty.
Implementation
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> arr; // Define a vector to store array elements
int length; // Variable to store the size of the array
// Input array size
std::cout << "Hey User, greetings!! Please enter the size of the array: ";
std::cin >> length;
// Check if the size is valid
if (length <= 0) {
std::cerr << "Error: Invalid array size!" << std::endl;
return 1; // Exit with error code
}
// Input array elements
std::cout << "Hey User, Greetings!! Please enter the array elements:" << std::endl;
for (int i = 0; i < length; ++i) {
int element;
std::cout << "Element " << i + 1 << ": ";
std::cin >> element;
arr.push_back(element); // Add element to the vector
}
// Using std::max_element to find the maximum value
std::vector<int>::iterator max_iter = std::max_element(arr.begin(), arr.end());
// Check if max_iter is valid (not equal to arr.end())
if (max_iter != arr.end()) {
int max_value = *max_iter;
std::cout << "The largest element present in the array is: " << max_value << std::endl;
} else {
std::cerr << "Error: Unable to find maximum value!" << std::endl;
}
return 0; // Exit normally
}
Output:
![How to Find Max Value in Array C++/>
<!-- /wp:html -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/how-to-find-max-value-in-array-cpp2.png)
The divide and conquer approach is basically used to derive the most efficient solution at a given point. They are basically done to test whether this problem can be optimized more or not. When we talk divide and conquer, it simply means that we have to make sure that we divide our bigger problem into smaller sub-problems till a stage where the problem cannot be divided any further. They are basically done when we need our program to run super-fast or when we have a huge amount of data set.
Approach
- First, we have to define a recursive function that will take the array, left index and right index as parameters. This function will keep dividing the array into smaller subarrays until we reach the base case or there are no smaller subarrays present.
- We also have to take care of the base case, which is if the left index is equal to the right index, which implies there is only one element present in the array. This means this is the maximum element present in the array, and we have to return it. If there isn't any element present, we have to just return 0.
- We then have to divide the current sub-array into two halves, one from left to middle and the other from middle to right.
- Then, we have to recursively find out the maximum element in both halves.
- Then, we have to merge the two answers and compare them to determine which one of the two is the maximum element overall and return that value.
Implementation
#include <iostream>
#include <vector>
// Creating a recursive function that will help us in finding the largest element in an array using the divide and conquer approach.
int findMax(const std::vector<int>& array, int left, int right) {
if (left == right) {
return array[left]; // If there is only a single element present, then we have to handle the base case, and we have to return it.
}
int mid = left + (right - left) / 2; // Evaluate the mid of the array
// Dividing the array into two equal parts and finding the largest element in one each.
int max_left = findMax(array, left, mid);
int max_right = findMax(array, mid + 1, right);
// Merge the results to find the overall maximum
return std::max(max_left, max_right);
}
int main() {
// Initialize array
std::vector<int> array = {33, 27, 92, 98, 91, 99, 84, 16, 5};
int size = array.size();
// Check if the array is empty
if (size == 0) {
std::cerr << "Hey USER!! You have made an error; the array is empty!" << std::endl;
return 1; // Exit with error code
}
// Find the maximum value using the divide-and-conquer approach
int max_value = findMax(array, 0, size - 1);
// Print the maximum value
std::cout << "Hey USER!! The largest element in the array is: " << max_value << std::endl;
return 0; // Exit normally
}
Output:
![How to Find Max Value in Array C++/>
<!-- /wp:html -->
<!-- wp:html -->
<div class=](https://static.tutorialandexample.com/cpp/how-to-find-max-value-in-array-cpp3.png)