Chapter 7.1. More Complex Loops

Once we have learned what loops are and what the for loops serve for, now is the time to take a look at other types of loops as well as some more complex loops constructions. They will expand our knowledge and help us solve difficult and challenging problems. In particular, we will discuss how to use the following program constructions:

loops with step

while loops

do-while loops

infinite loops

In the current chapter, we will also understand what the break operator is and how to break a loop. Also, using the try-catch construction, we will learn to keep track of errors during our program's execution.

Video: Chapter Overview

Introduction to More Complex Loops by Examples

Loops repeat a piece of code many times while a condition holds and usually changes the so called "loop variable" after each iteration. The loop variable using a certain step, e.g. 5 or -2. Example of a for loop from 10 down to 0, using a step -2:

Another example of loops is the do-while loop. It repeats a code block while a condition holds. For example, we can calculate the minimum number k, such that 2k2^k2​k​​ > 1,000,000,000, using the code below:

Sometime in programming we don't know in advance how many times to repeat a loop, neither we have a clear loop condition, so we may use infinite loop with exit condition inside the loop. For example, we want to print the first 5 results, matching certain condition, calculated inside a loop. We use infinite loop and exit it using the break operator: