course content

Course Content

C++ Loops

Break and Continue KeywordsBreak and Continue Keywords

There are two keywords that allow for more flexible work with loops: break and continue. They are control flow statements used within the loops to alter their behavior.

Continue

When the continue keyword is encountered within a loop, it immediately transfers control to the next iteration of the loop, skipping the remaining statements within the current iteration. In other words, it allows you to skip the current iteration of the loop and proceed with the next iteration.

A while loop runs while i is less than 5. Inside the loop, an if statement checks if i equals 1 or 3. If so, it increments i by 1 and continues to the next iteration with continue. For values of i not equal to 1 or 3, it prints "Hello" and the current value of i, then increments i by 1. The loop continues until i is no longer less than 5.

Break

When the break keyword is encountered within a loop, it immediately transfers control out of the loop, effectively ending the loop prematurely. In other words, it allows you to exit the loop before it would normally complete all its iterations, skipping any remaining iterations and the statements within them.

In this code, the loop is also will print "Hello" followed by the current value of i (0 in the first iteration), then increment i by 1. However, when i becomes 1, it will break out of the loop, so the loop will terminate when i equals 1.

Task

Output only odd numbers to the console using continue keyword.

Everything was clear?

Section 1. Chapter 4
toggle bottom row