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: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access