The while
loop
The while
loop is the simplest possible loop in C++. It repeatedly executes a specific set of statements block as long as the given condition is true.
The syntax of a while
statement is as follows:
while(/*condition*/) { /*body*/ }
The code above works as follows:
This includes two special cases:
The example below prints the sequence of numbers from 0 to 10.
Output:
0 1 2 3 4 5 6 7 8 9
More on the syntax
/*condition*/ must be an expression that evaluates to true or false. Often, comparison operators ==, !=, <, <=, >, >= are used, e.g. like i != j. Also, the condition may be just a number: non-zero value is interpreted as true, wheres 0 will be interpreted as false.
/*body*/ must be one or more statements. If /*body*/ contains a single statement, the curly braces may be omitted, but this is not recommended practice as it may lead to bugs in the code.
The example below shows some more complex ways to use a while loop.
#include <iostream> int main() { int i = 10; // print a sequence 10..1 while (i > 0) { std::cout << i << ' '; i--; } std::cout << '\n'; // same as above, i is decremented before being printed i = 10; while (i > 0) { i--; std::cout << i << ' '; } std::cout << '\n'; // same as above, with i-- integrated into the condition i = 10; while (i-- > 0) { // check i > 0 and then decrement i std::cout << i << ' '; } std::cout << '\n'; // the difference between --i and i-- i = 10; while (--i > 0) { // decrement i and check i > 0 std::cout << i << ' '; } std::cout << '\n'; // Since i is going towards zero, we may just check // whether it is equal to zero i = 10; while (--i != 0) { std::cout << i << ' '; } std::cout << '\n'; }
Output:
10 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1