Loop Breaks

Loop breaks in programming are control flow mechanisms used to prematurely exit a loop when a certain condition is met, regardless of whether the loop's termination condition has been satisfied. They are useful for terminating loops early to improve efficiency or to handle exceptional cases. For example, in a search algorithm, a loop break can be used to exit the loop as soon as the desired element is found, avoiding unnecessary iterations. Similarly, in input validation, a loop break can be used to stop prompting the user for input once valid data is provided. Loop breaks provide flexibility and allow programmers to tailor the behavior of loops to specific requirements, enhancing the overall functionality and efficiency of programs.

Select Languages

Examples

C

char* cars[] =
  {"Toyota", "Honda", "Mazda"};
  
int numItems = sizeof(cars) / sizeof(cars[0]);
char result[50];

for (int i = 0; i < numItems; i++) {
  if (cars[i] == "Honda") {
    sprintf(result, "Found at index %d", i);
    printf(result);
    break;
  }
  sprintf(result, "Visited index %d\n", i);
  printf(result);
}

C#

using System.Collections.Generic;

List<string> cars = new List<string>();
cars.Add("Toyota");
cars.Add("Honda");
cars.Add("Mazda");

for (int i = 0; i < cars.Count; i++) {
  if (cars[i] == "Honda") {
    Console.WriteLine("Found at index " + i + "\n");
    break;
  }
  Console.WriteLine("Visited index " + i + "\n");
}

C++

#include <iostream>
#include <vector>
using namespace std;

vector<string> cars = {"Toyota", "Honda", "Mazda"};
  
for (int i = 0; i < cars.size(); i++) {
  if (cars[i] == "Honda") {
    cout << "Found at index " << i << endl;
    break;
  }
  cout << "Visited index " << i << endl;
}

Go

import "fmt"

cars := []string{"Toyota", "Honda", "Mazda"};

for i := 0; i < len(cars); i++ {
  if (cars[i] == "Honda") {
    result := fmt.Sprintf("Found at index %d", i)
    fmt.Println(result)
    break
  } 
  result := fmt.Sprintf("Visited index %d", i)
  fmt.Println(result)
}

Java

import java.util.ArrayList;

ArrayList<String> cars = new ArrayList<>();
cars.add("Toyota");
cars.add("Honda");
cars.add("Mazda");

for (int i = 0; i < cars.size(); i++) {
  if (cars.get(i) == "Honda") {
    String result =
      String.format("Found at index %d", i);
    System.out.println(result);
    break;
  }    
  String result =
    String.format("Visited index %d", i);
  System.out.println(result);
}

JavaScript

const cars = ['Toyota', 'Honda', 'Mazda'];

for (let i = 0; i < cars.length; i++) {
  if (cars[i] === 'Honda') {
    console.log(`Found at index ${i}`);
    break;
  }
  console.log(`Visted index ${i}`);
}

Kotlin

val cars =
  mutableListOf<String>("Toyota", "Honda", "Mazda");
  
for ((index, car) in cars.withIndex()) {
  if (car == "Honda") {
    println("Found at index ${index}");
    break;
  }
  println("Visted index ${index}");
}

MatLab

cars = {"Toyota", "Honda", "Mazda"};
carCells = cellstr(cars);

for i = 1:length(carCells)
  if carCells(i) == "Honda"
    result = sprintf("Fount at index %d", i);
    fprintf(result);
    break;
  end

  result = sprintf("Visited index %d", i);
  fprintf(result);
  fprintf("\n");
end

PHP

$cars = array('Toyota', 'Honda', 'Mazda');

for ($i = 0; $i < count($cars); $i++) {
  if ($cars[$i] == 'Honda') {
    echo "Found at index {$i}\n";
    break;
  }
  echo "Visted index {$i}\n";
}

Python

cars = ['Toyota', 'Honda', 'Mazda']

for index, car in enumerate(cars):
  if car == 'Honda':
    print(f"Found at index {index}")
    break
  print(f"Visited index {index}")

R

cars <- list('Toyota', 'Honda', 'Mazda')
i <- 0

for (car in cars) {
  if (car == "Honda") {
    result <- sprintf("Found at index %d", i)
    print(result)
    break
  }
  result <- sprintf("Visited index %d", i)
  print(result)
  i <- i + 1
}

Ruby

cars = ['Toyota', 'Honda', 'Mazda']
i = 0;

for car in cars do
  if car == "Honda"
    puts "Found at index #{i}"
    break
  else
    puts "Visited index #{i}"
    i += 1
  end
end

Rust

let cars = ["Toyota", "Honda", "Mazda"];
let mut i = 0;

for car in cars {
  if car == "Honda" {
    let result = format!("Found at index {}", i);
    println!("{}", result);
    break;
  } 
  let result = format!("Visited index {}", i);
  println!("{}", result);
  i = i + 1;
}

Scala

import scala.util.control._;

var cars = Array("Toyota", "Honda", "Mazda");
val loop = new Breaks;

loop.breakable {
  for (i <- cars.indices) {
    if (cars(i) == "Honda") {
      println(s"Found at index $i");
      loop.break;
    }
    println(s"Visited index $i");
  }
}

Swift

var cars = ["Toyota", "Honda", "Mazda"];

for (i, car) in cars.enumerated() {
  if (car == "Honda") {
    print("Found at index \(i)")
    break;
  }
  print("Visited index \(i)")
}

TypeScript

const cars:string[] =
  ['Toyota', 'Honda', 'Mazda'];

for (let i = 0; i < cars.length; i++) {
  if (cars[i] === 'Honda') {
    console.log(`Found at index ${i}`);
    break;
  } else {
    console.log(`Visted index ${i}`);
  }
}

Copyright 2025. All Rights Reserved. IronCodeMan.