If the condition is false—that is, if val is not equal to currVal—then we execute the statement following the else. This statement is a block consisting of an output statement and two assignments. The output statement prints the count for the value we just finished processing. The assignments reset cnt to 1 and currVal to val,which is the number we just read.
C++(www.cppentry.com) uses = for assignment and == for equality. Both operators can appear inside a condition. It is a common mistake to write = when you mean == inside a condition.
EXERCISES SECTION 1.4.4
Exercise 1.17: What happens in the programpresented in this section if the input values are all equal What if there are no duplicated values
Exercise 1.18: Compile and run the program from this section giving it only equal values as input. Run it again giving it values in which no number is repeated.
Exercise 1.19: Revise the program you wrote for the exercises in § 1.4.1 (p. 13) that printed a range of numbers so that it handles input inwhich the first number is smaller than the second.
KEY CONCEPT: INDENTATION AND FORMATTING OF C++(www.cppentry.com) PROGRAMS
C++(www.cppentry.com) programs are largely free-format, meaning thatwhere we put curly braces, indentation, comments, and newlines usually has no effect onwhat our programs mean. For example, the curly brace that denotes the beginning of the body of main could be on the same line as main; positioned as we have done, at the beginning of the next line; or placed anywhere else we’d like. The only requirement is that the open curly must be the first nonblank, noncomment character following main’s parameter list.
Although we are largely free to format programs as we wish, the choices we make affect the readability of our programs. We could, for example, have written main on a single long line. Such a definition, although legal, would be hard to read.
Endless debates occur as to the right way to format C or C++(www.cppentry.com) programs. Our belief is that there is no single correct style but that there is value in consistency. Most programmers indent subsidiary parts of their programs, as we’ve done with the statements inside main and the bodies of our loops. We tend to put the curly braces that delimit functions on their own lines. We also indent compound IO expressions so that the operators line up. Other indentation conventions will become clear as our programs become more sophisticated.
The important thing to keep in mind is that other ways to format programs are possible. When you choose a formatting style, think about how it affects readability and comprehension. Once you’ve chosen a style, use it consistently.