What is the largest number in this list of numbers?
23 | 45 | 26 | 19 | 48 | 74 | 68 | 43 |
57 | 30 | 44 | 28 | 50 | 60 | 38 | 23 |
94 | 47 | 83 | 91 | 72 | 77 | 76 | 55 |
82 | 11 | 32 | 31 | 58 | 21 | 40 | 80 |
56 | 88 | 41 | 13 | 70 | 41 | 53 | 62 |
21 | 62 | 78 | 95 | 37 | 58 | 61 | 82 |
18 | 43 | 12 | 17 | 83 | 65 | 20 | 90 |
71 | 77 | 10 | 51 | 35 | 91 | 59 | 52 |
27 | 58 | 65 | 74 | 88 | 42 | 63 | 32 |
87 | 33 | 72 | 64 | 18 | 15 | 58 | 27 |
How did you find it?
I think that what you did was this: you looked at each number once and you remembered the largest that you had seen up to that point. After you had looked at all the numbers, then you knew which one was the largest.
There is another point to make: you initialized the largest number with the first number in the list.
This same method can be applied in a program.
Using this technique in the above list:
Read the first number and set LargestSoFar equal to it.
LargestSoFar | 23 |
In a loop, read each NewNumber, and compare it to LargestSoFar. If NewNumber is greater than LargestSoFar, then set LargestSoFar to the NewNumber.
LargestSoFar | NewNumber |
23 | 45 |
45 (changed) | 26 |
45 | 19 |
45 | 48 |
48 (changed) | 74 |
74 (changed) | 68 |
74 | 43 |
74 | 57 |
etc... | etc... |