Loops and Control Flow

while Loop

A while loop repeats as long as the condition is true. Used when the number of iterations isn’t known in advance.

Basic Structure:

while (condition) {
    // code block
}
Loading...
Output:

do-while Loop

A do...while loop always executes at least once. Condition is checked after the block.

Basic Structure:

do {
    // code block
} while (condition);
Loading...
Output:

for Loop

The for loop is compact and ideal when the number of iterations is known.

Basic Structure:

for (initialization; condition; update) {
    // code block
}
Loading...
Output:

break Statement

Use break to exit a loop early

Loading...
Output:

continue Statement

Use continue to skip the rest of the current loop iteration and continue with the next.

Loading...
Output:

Nested Loops

A loop inside another loop is useful for iterating over 2D structures like grids or matrices.

Loading...
Output:

User-Controlled Termination

You can allow a user to stop a loop using input. For example, loop until they enter -1.

Loading...
Output:

Practice Question

What will this print?

0123
0124
1234
Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic