How to Find Max Value in C++ Array

C-Plus-Plus-array

In this tutorial, we are going to learn about different methods of how to Find Max Value in C++ Array. We will learn this by using multiple techniques by using basic to advanced C++.so let us begin.

1.Find max value in C++ array entered by user


In this example program, we are first taking n number of elements from the user. Then we are finding the largest number from this input array. When we have the result then finally display it.

  • We have an array of length 100.
  • We are asking users to enter the length or number of elements in the array.
  • We are running a for loop till the length of the array and store elements entered by the user in Testarr
  • Again running loop till Arraylen and comapring element and swapping value to compare with finding the max value

C++ Program to find max value in Array

#include <iostream>
using namespace std;
int main()
{ 
   int Arraylen;
  float Testarr[100];
  cout << "Enter the Desired length of array between 1 to 100: ";    
  cin >> Arraylen;    cout << endl;
   for(int k = 0; k < Arraylen; ++k) 
   {
      cout << "Enter the elements at index : " << k  << " : ";        
       cin >> Testarr[k];   
     }
   for(int i = 1;i < Arraylen; ++i)  
   {              
       if(Testarr[0] < Testarr[i]) 
          Testarr[0] = Testarr[i];    
   }    
    cout << "The Largest Number in input Array is = " << Testarr[0];
    return 0;
}

Output

Enter the Desired length of array between 1 to 100: 5

Enter the elements at index : 0 : 12
Enter the elements at index : 1 : 50
Enter the elements at index : 2 : 60
Enter the elements at index : 3 : 100
Enter the elements at index : 4 : 34
The Largest Number in input Array is = 100

2.STL algorithm to find max value in array


In this example, we are going to learn about the STL algorithm method max_element() to find the max element or largest value in an array.

C++ Program to find max value in Array STL algorithm

#include <iostream>
#include <algorithm>
using namespace std;
 
int main()
{
    int Testarr[] = { 45, 32, 21, 61, -14, 3 };
 
    int *largest = std::max_element(std::begin(Testarr), std::end(Testarr));
 
    std::cout << "The largest element in the Array is " << *largest << std::endl;
 
    return 0;
}

Output

The largest element in the Array is 61

Summary

In this post, we have learned how to Find Max Value in C++ Array.