The control structure while

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. Control structures

    /

  5. The control structure while

The loop structure while

The control structure while is similar to the structure if except that it executes the code inside its braces as long as the condition inside its parentheses () stays true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream> int main() { int nbOfTimes = 5; while(nbOfTimes > 0) { //Subtracts 1 from “nbOfTimes” nbOfTimes--; //Outputs "Hello.", followed by a new line, to the console. std::cout << "Hello." << std::endl; } return 0; }

In the example above, the text “Hello” is written 5 times in the console. After that, the variable nbOfTimes equals 0 and the condition inside the parentheses () of the while statement becomes false and therefore the loop stops.

Do while

The structure do while is very similar to the while structure, except that it executes the instructions inside its braces once (No matter what) and then repeats them as long as the condition inside its parentheses is true. It is coded by writing the keyword do followed by the instructions inside braces and then the while statement ended by a semicolon ;.

An example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> int main() { int n = 2; do { n--; std::cout << "Hello." << std::endl; } while(n > 0); return 0; }

In the example above, the text "Hello." is written 2 times in the console.

In the example below, the text "Hello." is outputted to the console only once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> int main() { int n = 0; do { n--; std::cout << "Hello." << std::endl; } while(n > 0); return 0; }

(Note that the while statement in the do while structure ends with a semicolon ;)

In the example above, if a while structure had be used instead of do while, nothing would have been printed to the console:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> int main() { int n = 0; while(n > 0) { n--; std::cout << "Hello" << std::endl; } return 0; }

Braces

Just a reminder that with control structures, braces are optional if there is only one instruction inside them.

1
2
3
4
5
6
7
8
9
#include <iostream> int main() { while(true) std::cout << "Infinite loop." << std::endl; return 0; }

The example above prints the text "Infinite loop." to the console without ever stopping. The only way to make it stop is to close the console window.

This is a good moment to tell you to be careful with loops. It is important to make sure they stop at some point, unlike in the example above. Infinite loops (usually) make programs either freeze or crash.