When studying the conditional operator, we touched on the topic of finding the maximum number from several entered numbers. In the "Maximum of four numbers" problem, we used the following algorithm:
1. Assign the value of the variable Max to the first of four variables
2. If the value of the second variable is greater than the value in the maximum variable, then replace the value of the maximum variable with the value of the second variable
3. If the value of the third variable is greater than the value in the maximum variable, then replace the value of the maximum variable with the value of the third variable
4. If the value of the fourth variable is greater than the value in the maximum variable, then replace the value of the maximum variable with the value of the fourth variable
It can be seen that we compared each number (denoted by X) with the variable maximum, as follows
pseudocode:
input Х
if (maximum < X), then
maximum = X
The main thing in this code is to determine what initial value the variable maximum will have.
Usually, when solving the problem of finding the maximum or minimum, the initial value of the variable maximum is assigned equal to the first number.
Thus, the above code must be executed 1 times less than the number of numbers (since the first number must be entered and stored as the initial value of the variable maximum).
If we have the number of numbers set from the keyboard (for example, into the variable n), then we can organize a cycle (from 2 to n), using the same variable to store the number.
Try to write the whole program yourself