O'Reilly logo

C++ Primer, Fifth Edition by Barbara E. Moo, Josée Lajoie, Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

1.4.4. The if Statement

Like most languages, C++ provides an if statement that supports conditional execution. We can use an if to write a program to count how many consecutive times each distinct value appears in the input:

#include <iostream>int main(){    // currVal is the number we're counting; we'll read new values into val    int currVal = 0, val = 0;    // read first number and ensure that we have data to process    if (std::cin >> currVal) {        int cnt = 1;  // store the count for the current value we're processing        while (std::cin >> val) { // read the remaining numbers            if (val == currVal)   // if the values are the same                ++cnt;            // add 1 to cnt            else { // otherwise, print the count ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required