Thursday, February 25, 2021 16:55

Table of contents >> Introduction > While loop

While loop

Loops are a special kind of instructions that repeat a piece of code a specific number of times or until a special condition becomes True. There are also loops that never end, called infinite loops, and they are rather errors than useful code. There are 4 kinds of repeating code instructions: for loop, foreach loop, while loop and do-while loop

The most simple is the While loop. Its code looks like this:

In the above code, the condition is any expression that returns a Boolean value (True or False), and it determines for how long the loop runs. The instructions are the piece of code that will be executed again and again, while the loop condition is True. A While loop basically evaluates the loop condition. If the condition is True, the instructions are executed. When the last instruction is executed, the loop condition is evaluated again, and the process repeats until the condition evaluates as False, when the execution continues with the code following after the While body.

Loops execute extremely fast, and they can be EXTREMELY high CPU power consumers, so, do not abuse them. Loops can never run their instructions, if their condition is never evaluated as True, or they can run forever, if their condition never evaluates as False. Notice that while a loop runs, the program might become unresponsive (the processor is too busy executing the loop’s instructions, to actually process any other input, like mouse clicks or key presses).

The following example demonstrates the usage of a While loop:

And this is the result:

while loop

The concepts explained in this lesson are also shown visually as part of the following video:



Tags: ,

Leave a Reply

Follow the white rabbit