In this C++ tutorial, you shall learn how to write a program to find the largest number in the given array.

C++ Find Largest Number in Integer Array

To find the largest of elements in an integer array,

  1. Initialize largest with first element of array.
  2. For each element in the array:
    1. Compare largest with this element.
    2. If largest is less than this element, then update largest with the element.
  3. largest contains the largest number in given integer array.

We will use C++ Less than Operator for comparison.

Examples

1. Find the largest number in the array {2, 4, 6, 8, 0, 1}

In the following example, we take an integer array initialized with some elements, and find the largest number of the elements of this array.

main.cpp

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int x[] = {2, 4, 6, 8, 0, 1}; //integer array
    int len = sizeof(x) / sizeof(x[0]); //get array length
    
    // find largest only if there is atleast one element in array
    if ( len > 0 ) {
        int largest = x[0]; //assume that first element is largest
        
        for ( int i = 1; i < len; i++ ) {
            if ( largest < x[i] ) {
                largest = x[i]; //update largest
            }
        }
        
        cout << "Largest : " << largest << endl;
    } else {
        cout << "No elements in the array." << endl;
    }
}

Output

Largest : 8
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find the largest of elements of an integer array, with the help of example C++ programs.