1.4.1. The while Statement

A while statement repeatedly executes a section of code so long as a given condition is true. We can use a while to write a program to sum the numbers from 1 through 10 inclusive as follows:

#include <iostream>int main(){    int sum = 0, val  = 1;    // keep executing the while as long as val is less than or equal to 10    while (val <= 10)  {        sum += val;   // assigns sum + val to sum        ++val;        // add 1 to val    }    std::cout << "Sum of 1 to 10 inclusive is "              << sum << std::endl;    return 0;}

When we compile and execute this program, it prints

Sum of 1 to 10 inclusive is 55

As before, we start by including the iostream header and defining main. Inside main we define two int variables: ...

Get C++ Primer, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.