Stroustrup's PPAP: Chapter 4 Exercise 3

Hi,

I am learning C++ from Stroustrup's Programming Principles and Practice Using C++. I am on exercise 3 of chapter 3. Although I have solved the problem, I cannot understand how Stroustrup does it. In particular, this part goes over my head:

1
2
3
4
		// update the "running" values:
		sum += val;
		if (val<min) min = val;
		if (max<val) max = val;


Can you help? The complete code is here: http://www.stroustrup.com/Programming/Solutions/Ch4/e4-3.cpp
He has a variable sum that is initialized to zero before the loop. Each value that the user enters is added to the sum.

In case you don't know sum += val; is just a shorter way of writing sum = sum + val;

To keep track of the maximum value entered he has a variable called max that is initialized to zero. For each value he checks to see if the new value is greater than the current max. If that is the case he updates the max variable, so max will always equal the greatest of the values that the user has entered so far.

The code for keeping track of the smallest value is similar but I think there is a mistake in the solution you linked. min is initialized to zero, which is smaller than the smallest allowed value 1, so the min variable will always be zero. I think min should have been initialized to a very large value that is larger than anything that the user enters. Initializing min to infinity would probably have been the best option (assuming infinity is supported).
1
2
double min = 0;
double min = std::numeric_limits<double>::infinity();
Last edited on
Understand! Thank you, Peter Olsson!
Topic archived. No new replies allowed.