C++ How To Find the Largest Element in an Array
Find the Largest Element in an Array
Start with the first element, and keep the largest value you find:
Example
int numbers[] = {45, 12, 85, 32, 89, 39};
int largest = numbers[0];
for (int num : numbers) {
if (num > largest) {
largest = num;
}
}
cout << "Largest element: " << largest;
Explanation:largest starts as the first element (45).
Each time the loop finds a larger number, largest is updated.
Related Pages
C++ How To Find Min and Max in an Array