Dart – Loop Control Statements (Break and Continue)

Dart supports two types of loop control statements:

  1. Break Statement
  2. Continue Statement

Break Statement:

This statement is used to break the flow of control of the loop i.e if it is used within a loop then it will terminate the loop whenever encountered. It will bring the flow of control out of the nearest loop.

Syntax:

break;


Example 1: Using break inside while loop

void main()
{
int count = 1;
while (count <= 10) {
    print("you are inside loop $count");
    count++;

    if (count == 4) {
        break;
    }
}
print("you are out of while loop");
}

output:

you are inside loop 1

you are inside loop 2

you are inside loop 3

you are out of while loop

Initially count value is 1, as it goes inside loop the condition is checked, 1 <= 10 and as it is true the statement is printed variable is increased and then condition is checked, 2 == 4, which is false. Then the loop is followed again till the condition 4 == 4 is encountered and the flow comes out of the loop and then last print statement is executed.

Example 2: Using break inside for loop

void main()
{
for (int i = 1; i <= 10; ++i) {
if (i == 2)
break;    
print("you are inside loop $i");
}

print("you are out of loop");
}

Output:

you are inside loop 1
you are out of loop
Continue Statement:
While the break is used to end the flow of control, continue on the other hand is used to continue the flow of control. When a continue statement is encountered in a loop it doesn’t terminate the loop but rather jump the flow to next iteration.

Syntax:
continue;

Example 1: Using continue inside while loop

void main()
{
int count = 0;
while (count <= 10) {
    count++;

    if (count == 4) {
        print("Number 4 is skipped");
        continue;
    }

    print("you are inside loop $count");
}

print("you are out of while loop");
}

Output:

you are inside loop 1

you are inside loop 2

you are inside loop 3

Number 4 is skipped

you are inside loop 5

you are inside loop 6

you are inside loop 7

you are inside loop 8

you are inside loop 9

you are inside loop 10

you are inside loop 11

you are out of while loop

Here control flow of the loop will go smooth but when count value becomes 4 the if condition becomes true and the below statement is skipped because of continue and next iteration skipping number 4

Leave a comment

Your email address will not be published. Required fields are marked *