8.8. break Statement

Synopsis: break;

The break statement is used within loops to exit immediately. The execution is continued at the first statement after the loop.

Example 8.9. break statement

{
    integer a = 0;

    repeat 
    {
	y2milestone("Current a: %1", a);
	a = a + 1;
	if (a == 7) break;		// Exit the loop here, if a equals 7.
    } until (a > 10);		// Value 10 will never be reached.

    y2milestone("Final a: %1", a);	// This prints 7.
}

Example 8.10.  break statement in foreach

{
    foreach (string text, ["a", "new", "string", "break"], {
	// finishes the foreach loop
	if (text == "string") break;
	
	// "string" and "break" will never get here
	y2milestone("Current text is '%1'", text);
    });
}

Example 8.11.  Nice break statement in foreach

{
    // list of found prime-number
    list <integer> found = [];
    // start with number
    integer number = 2;
    // finish with number
    integer max_number = 20000;
    
    while (number < max_number) {
	boolean not_found = true;
	
	// try all already found numbers
	foreach (integer try, found, {
	    if (number % try == 0) {
		not_found = false;
		break;
	    }
	});
	
	if (not_found)
	    found = add (found, number);

	number = number + 1;
    }
    
    y2milestone("Sum:   %1", size(found));
    y2milestone("Found: %1", found);
}

Example 8.12.  break statement in listmap

{
    integer counter = 0;

    // goes through the list and returns a map
    // made of this list
    map new_map = listmap (string text,
        ["a", "new", "string", "break"], 
    {
        // finishes the listmap loop
        if (text == "string") break;

        counter = counter + 1;
	// returns one "key : value" pair of the new map
        return $[text : counter];
    });
    
    y2milestone("Returned map: %1", new_map);
}
[Note]Note

The break statement can be used for all loop statments and also statments: listmap, mapmap, list-based maplist, map-based maplist, list-based foreach, map-based foreach, list-based filter, map-based filter.