C++ Program – Find Largest Number in Integer Array
To find the largest of elements in an integer array,
- Initialize
largest
with first element of array. - For each element in the array:
- Compare
largest
with this element. - If
largest
is less than this element, then updatelargest
with the element.
- Compare
largest
contains the largest number in given integer array.
We will use C++ Less than Operator for comparison.
Examples
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
#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.