Well, array is the collection of elements of same data type. Like either all the elements can be integer, float or character or of any other data types.
Finding largest or smallest element in an array is all about comparison between the elements. By comparing only we will be able to find largest element and we can switch its position with its adjacent element.
Here, we have visit all the elements in an array to find out the largest one. For that we need looping structure.
we have assumed largest is on 0 position. so we are comparing all other elements with arr[largest]. And reassigning the largest when condition is true.
We do it till we get the largest one.
Complete code:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {4, 7, 2, 4, 9, 5, 6, 12};
int n = sizeof(arr) / sizeof(int);
int largest = 0;
for (int i = 0; i < n; i++)
{
if (arr[largest] < arr[i + 1])
{
largest = i;
}
}
cout << "Largest element is: " << arr[largest];
}