Break statement in Dart Programming


The break statement is used when we want to break or terminate the execution of a loop. Once the break statement is reached the control is transferred from the current loop to whatever is written after the loop.

It is mostly used in the conditional statement and also in loops of all types. It is present in almost all popular programming languages.

Syntax

break;

Now let's take a very simple example, where we have a variable named num and we are iterating until num > 5. Suppose we want to exit from the loop when we know that the value inside the num variable has become 6, we can do that with the help of the break statement.

Example

Consider the example shown below −

 Live Demo

void main(){
   var num = 10;
   while(num > 5){
      if(num == 6){
         print("Number became 6, so braking.");
         break;
      }
      num--;
   }
   print("Now, num should be 6 : ${num}");
}

Output

Number became 6, so braking.
Now, num should be 6 : 6

Example

Let's take one more example, where we make use of the for-in loop.

Consider the example shown below −

 Live Demo

void main(){
   var name = "apple";
   var fruits = ["mango","banana","litchi","apple","kiwi"];
   for(var fruit in fruits){
      if(fruit == name){
         print("Don't need an apple!");
         break;
      }
   }
   print("After the break, this should be printed!");
}

Output

Don't need an apple!
After the break, this should be printed!

Updated on: 21-May-2021

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements