Unfortunately, the point in CS 101 classes is often to learn how to traverse arrays and track information yourself, so using the Standard Library for this simple task (what a normal C++ programmer
should do) is out (because it is
not what
you should do).
To loop over an array, you need each element’s
index: 0, 1, 2. Use the index to get the element value:
1 2 3 4 5
|
int xs[] = { 2, 7, 3, 9, 4 };
cout << "The first element is " << xs[0] << "\n";
cout << "The second element is " << xs[1] << "\n";
…
|
This 0, 1, 2, … indexing scheme helps when you want to loop over the array. You just need to know how many elements are in the array. (In this case, there are 5.)
1 2
|
for (int n = 0; n < 5; n++)
cout << "The " << (n+1) << "th element is " << xs[n] << "\n";
|
The 1th element is 2
The 2th element is 7
The 3th element is 3
The 4th element is 9
The 5th element is 4 |
All of this you could have learned by simply googling something like “C/C++ arrays” and “C/C++ arrays tutorial”.
Next, to the algorithm. Given the list:
2 7 3 9 4
How do I find the largest element? How do I prove it is the largest?
Remember, the computer cannot look at
all the elements at the same time. It can, however, compare
two numbers.
I can compare 2 and 7. 7 is larger.
I can compare 7 and 3. 7 is larger.
I can compare 7 and 9. 9 is larger.
I can compare 9 and 4. 9 is larger.
9 is largest.
Do you see the pattern?
You need to keep track of the
current largest value.
Think on it.
Hope this helps.