Can someone explain this code's logic for me?

Hi, I need help in this code. I know the logic of this code but can't understand the int n and it's purpose. So here is the code. So the function's purpose is to determine the highest integer in an array. This function works well but I still don't get the part int n = 0. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int mymaximum(int a[], int numberOfElements)
{
    int n = 0;
    
    for (int i = 0; i < numberOfElements; i++) //for loop from 0 to the number of elements as i
    {
        if (a[i] > n) 
        {
            n = a[i]; 
        }
    }
    
    return n; 
    
  
}
int n = 0;

This declares the variable n, which has a scope of only being within the function. It is initialized to 0. This is needed so the first time you compare it to a number in the array it has a value to be compared to.
The variable n keeps track of the highest value the loop has encountered so far. If a higher value is found n is updated. After the loop n will contain the highest value of all array elements.

Note that because n is initialized to 0 it will not give you the correct value if all array elements have negative values.
Topic archived. No new replies allowed.