Course Content
Introduction to Dart
Introduction to Dart
Break and Continue
break
In Dart, break is a statement used to exit a loop. The break statement can be used in any loop, including while
, for
, and do-while
loops.
The syntax for the break
statement is as follows:
When the break statement is encountered in code, it terminates the execution of the loop in which it is located. This means that any other iterations of the loop will not be executed.
Example
The break
statement is often used to exit a loop if a condition meets specific requirements. For example, the following code prints all numbers from 1 to 10, but it breaks the loop if it encounters the number 5:
main
void main() { int counter = 1; while (counter <= 10) { if (counter == 5) { break; } print(counter); counter++; } }
continue
Continue is a statement used to skip the current iteration of a loop. The continue statement can be used in any loop, including while
, for
, and do-while
loops.
The syntax for the continue
statement is as follows:
Example
The continue
statement is often used to skip certain values or conditions
main
void main() { List<String> actions = ["go", "jump", "stop", "go", "go", "stop", "jump", "stop", "go", "go", "stop"]; for (String item in actions) { if (item == "stop"){ continue; } print(item); } }
As you can see, the continue statement allows us to control which list items will be output to the console.
Thanks for your feedback!