# C++ Notes: Loop Example - Maximum of input numbers

Often a `cin` loop can contain all of the computation for simple programs. Here are two ways to solve a common problem - find the maximum value in a series of numbers.

The first solution contains the heart of the correct solution, but it has some weaknesses. The second solution improves on the first.

## Max with some problems

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ``` ```// loops/cin-max-flakey.cpp - Finds max int in input. // Purpose of this example. // 1. To illustrate algorithm to find maximum. // 2. To show common problems to be fixed in loops/cin-max-robust.cpp // Eg, what happens if all numbers are negative? No input? // Fred Swartz - 2003-08-28 #include using namespace std; int main() { int max = 0; int n; while (cin >> n) { if (n > max) { max = n; } } cout << "Maximum is " << max << endl; return 0; } ``` The text from the above example can be selected, copied, and pasted into an editor.

## Max with some improvements

The following program checks to make sure there is at least one number to be read. Also, it uses the first value to initialize the maximum, which guarantees that it will work regardless of the range of values.
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ``` ```// loops/cin-max-robust.cpp - Finds max int in input. // Purpose of this example. // 1. To illustrate algorithm to find maximum. // 2. To show solution to negative number or missing input. // Fred Swartz - 2003-08-28 #include using namespace std; int main() { int max; int n; if (cin >> max) { // Sets initial value of max while (cin >> n) { if (n > max) { max = n; } } cout << "Maximum is " << max << endl; } else { cout << "No input!" << endl; } return 0; } ``` The text from the above example can be selected, copied, and pasted into an editor.

Another way to insure that the maximum is correctly initialized is to set it to the minimum possible int value. The range of an int depends on the the compiler and underlying machine architecture, but the minimum value is in `INT_MIN` (from header file `<climits>`). But there is still the problem of no input values.