1.4.4 The if Statement
Like most languages, C++(www.cppentry.com) provides an if statement that supports conditional execution. We can use an if to write a programto count how many consecutive times each distinct value appears in the input:
- #include <iostream>
- int main()
- {
-
- int currVal = 0, val = 0;
-
- if (std::cin >> currVal) {
- int cnt = 1;
- while (std::cin >> val) {
- if (val == currVal)
- ++cnt;
- else {
- std::cout << currVal << " occurs "
- << cnt << " times" << std::endl;
- currVal = val;
- cnt = 1;
- }
- }
-
- std::cout << currVal << " occurs "
- << cnt << " times" << std::endl;
- }
- return 0;
- }
If we give this program the following input:
- 42 42 42 42 42 55 55 62 100 100 100
then the output should be
- 42 occurs 5 times
- 55 occurs 2 times
- 62 occurs 1 times
- 100 occurs 3 times
Much of the code in this programshould be familiar fromour earlier programs. We start by defining val and currVal: currVal will keep track of which number we are counting; val will hold each number as we read it from the input. What’s new are the two if statements. The first if
- if (std::cin >> currVal) {
-
- }
ensures that the input is not empty. Like a while, an if eva luates a condition. The condition in the first if reads a value into currVal. If the read succeeds, then the condition is true and we execute the block that starts with the open curly following the condition. That block ends with the close curly just before the return statement.
Once we know there are numbers to count, we define cnt, which will count how often each distinct number occurs. We use a while loop similar to the one in the previous section to (repeatedly) read numbers from the standard input.
The body of the while is a block that contains the second if statement:
- if (val == currVal)
- ++cnt;
- else {
- std::cout << currVal << " occurs "
- << cnt << " times" << std::endl;
- currVal = val;
- cnt = 1;
- }
The condition in this if uses the equality operator (the == operator) to test whether val is equal to currVal. If so, we execute the statement that immediately follows the condition. That statement increments cnt, indicating that we have seen currVal once more.