Menu
Coddy logo textTech

Using 'break' in Loops

Part of the Fundamentals section of Coddy's Dart journey — lesson 45 of 94.

The break statement allows you to exit a loop immediately, regardless of the loop condition.

Create a for loop that stops when it reaches 3:

void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      break;
    }
    print(i);
  }
}

After executing the above code, the output will be:

1
2

Use break to exit a while loop when a condition is met:

void main() {
  int count = 1;
  
  while (count <= 10) {
    print(count);
    if (count == 4) {
      break;
    }
    count++;
  }
}

After executing the above code, the output will be:

1
2
3
4
challenge icon

Challenge

Beginner

In this challenge, you'll practice using the break statement in a loop. The break statement allows you to exit a loop early when a certain condition is met.

Complete the code to find the first number in the list that is divisible by 5. Once you find it, use break to exit the loop and print the result.

Expected output:

Checking number: 7
Checking number: 12
Checking number: 15
Found it! 15 is divisible by 5

Cheat sheet

The break statement allows you to exit a loop immediately, regardless of the loop condition.

Using break in a for loop:

for (int i = 1; i <= 5; i++) {
  if (i == 3) {
    break;
  }
  print(i);
}

Using break in a while loop:

int count = 1;

while (count <= 10) {
  print(count);
  if (count == 4) {
    break;
  }
  count++;
}

Try it yourself

void main() {
  // List of numbers to check
  List<int> numbers = [7, 12, 15, 20, 25];
  
  // Variable to store the first number divisible by 5
  int result = 0;
  
  for (int number in numbers) {
    print('Checking number: $number');
    
    // TODO: Check if the number is divisible by 5
    // If it is, store it in the result variable and use break to exit the loop
    
  }
  
  // Print the result
  if (result > 0) {
    print('Found it! $result is divisible by 5');
  } else {
    print('No number divisible by 5 was found');
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals