I had to write a code that took ten numbers from the user, put them in an array. The program would then return highest number. I did a little research and I found a solution online, everything works fine the problem is that I do not know why. I know how the user input portion works, but returning the highest number part is confusing. I know why the for loop is being used. I was hoping some one could explain it very slowly and please don't use big words. Lines 15, 19, and 20.
#include <iostream>
usingnamespace std;
int main()
{
int max;
int i;
int j;
int number[10];
//Read the numbers from the user.
cout << "Enter ten numbers and I will return the highest number of the bunch. ";
for (i = 0; i < 10; i++)
{
cin >> number[i];
}
max = number[0];
// Finding the high number
for (j = 1; j < 10; j++)
{
if (max < number[j])
max = number[j];
}
cout << "The Maximum number is: " << max << endl;
return 0;
}
Line 15 sets the max as the first element in the array.
The for loop then cycles through the rest of the array.
Line 19 compares the "max" against the next element in the array. If the following element is higher than the "max" then it sets the max as the current element in the array. It does this for the length of the array.