# Program to find the max value in the array with explanation in C++

posted Sep 10

In this program we will find the element of maximum or you can say largest value in the array. First, we will ask the user to enter the elements of the array then the program will print the largest element.

# Code

``````#include <iostream>
using namespace std;
int main(){

int n, largest;
int num[50];
cout<<"Enter number of elements you want to enter: ";
cin>>n;

for(int i = 0; i < n; i++) {
cout<<"Enter Element "<<(i+1)<< ": ";
cin>>num[i];
}

largest = num[0];
for(int i = 1;i < n; i++) {

if(largest < num[i])
largest = num[i];
}
cout<<"Largest element in array is: "<<largest;
return 0;
}``````

## Output

```Enter number of elements you want to enter: 6
Enter Element 1: 12
Enter Element 2: 45
Enter Element 3: 154
Enter Element 4: 62
Enter Element 5: 789
Enter Element 6: 2
Largest element in array is: 789```

### Explanation

If a user enters 6 i.e., the number of arrays is 6 (we know that max is 50.) Then the user enters the 6 different elements in the array. Those elements are stored in memory as num[0], num[1], num[3] and so on.
When the loop starts iterating, the first element is assigned as the largest value which is now 23. And when the second loop runs its value will be compared to the first element. If it will be bigger than the first one, then it will be assigned as the largest value in the array. Such that we will compare all the numbers until the end of the loop.

In short:
N is the number of elements in the array. Loop runs from 0 to n, in such a way that the first element entered by the user is stored in num[0], second in num[1] and so on.
Then it will store the first array element in the largest variable. After that it will compare the largest variable with every element of the array. If there is an element which is greater than the largest variable value, then we copy that variable to largest, this way we have the largest element copied to the variable named “largest” at the end of the loop.

100 points
7 2