Loops can execute a block of code as long as a specified condition is reached. They are handy because they save time, reduce errors, and make code more readable.
while LoopThe while loop loops through a block of code as long as a specified condition is true.
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
In the example above, the code in the loop will run, over and over again, as long as i is less than 5. Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end (an infinite loop)!
do/while LoopThe do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Use loops whenever you need to repeat an action multiple times!
Which variant of the while loop guarantees that the code block will execute at least once?