Maximum number in an array in C++

'high' is outside the loop
#include <iostream>
using namespace std;

int main(){
    int n,high;
    cin >> n;
    int arr[n]={};
    for(int i=0; i<n; i++){
        cin >> arr[i];
    }
    high = arr[0];
    for(int i=0; i<n; i++){
        if(high<arr[i]){
            high = arr[i];
        }
    }
    cout << "High ==> " << high << endl;
    return 0;
}

'high' is inside the loop
#include <iostream>
using namespace std;

int main(){
    int n,high;
    cin >> n;
    int arr[n]={};
    for(int i=0; i<n; i++){
        cin >> arr[i];
    }
    for(int i=0; i<n; i++){
        high = arr[0];
        if(high<arr[i]){
            high = arr[i];
        }
    }
    cout << "High ==> " << high << endl;
    return 0;
}

Here is my input,

4
2 5 6 4

If I use high = arr[0]; outside the loop then output is High ==> 6, which is correct. But if i use high = arr[0]; inside the loop then, output is High ==> 4, which is incorrect.

But, why I should not expect High ==> 6 while I used it inside or how this High ==> 4 is coming?

When this is inside of the loop, you reset high to arr[0] on every single loop iteration.

2 Likes

In the latter, you are setting high to the first element in the array every time through the for loop. So you aren’t keeping a running total for high, and thus the last element in the array that is greater than the first element in the array will always be returned.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.