Break And Continue

Break

Break is used to forcefully stop loop even if it's condition is met.

Output:

line 4 ends the loop though it's condition is fulfilled.

Value of sum is formed by adding i to it (1 + 2 + 3 + 4 + 5 + 6 = 21).

Continue

Continue skips the current iteration of the loop.

Output:

line 3stops the current iteration thus 4 isn't printed.

Unlike breakit doesn't skip the entire loop.

Else in for loop

Else block after for loop executes only if the loop's not forcefully terminated (like using break).

Example:

Output:

The first loop is not terminated (because i == 10 is always false). For that reason A is printed.

The second loop is terminated (because i == 2 is true in one of the loop's iteration). For that reason B is not printed.