While & Do/While Loops

While Loop

Probably the simplest loop structure, this code block will run if and only if the condition is true. Once it becomes false, the loop stops. You can also break out of the loop with a break; statement. Keep in mind that the while loop may not run at all, depending on the condition.

Syntax

The syntax of a While loop is some of the simplest possible:

Example 1 - Infinite Loop

Example 2 - Until a Value

Clicking the blue "Powered By" button will open this example in a new tab

Do While Loop

The Do While is a variation on the While. It is guaranteed to run at least once but it will only loop back to the top if the condition is true.

Syntax

The syntax is similar to the While loop but notice the differences - especially the semicolon ending the statement.

Example 3 - Not Zero

Example 4 - Print a Box

Clicking the blue "Powered By" button will open this example in a new tab

Last updated