Break Statements
The Break Statement can alter the flow of a normal loop. Loops iterate over a block of code until the Boolean expression is false, but sometimes we wish to terminate the iteration or even the whole loop early. The break statement is used in these cases.
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break will terminate the innermost loop only. Note you will most likely need to place an if statement inside the loop to use the break statement, because if you just have a break statement all by itself inside a loop, it will always hit it the first time through and that is not really useful!
The break statement (in most computer programming languages), takes the generic form of:
WHILE bolean expression
statement_1
statement_2
…
IF (Boolean expression) THEN
ENDIF
counter = counter + 1
ENDWHILE
FOR counter in range(n)
statement_1
statement_2
…
IF Boolean expression THEN
ENDIF
ENDFOR
In this example program, the user is asked to enter a positive integer and the program will count how many times it goes through the loop until it reaches that number, except it will always stop when it hits 5!
Top-Down Design for the Break Statement
Flowchart for the Break Statement
Pseudocode for the Break Statement
GET positive_integer
FOR (int counter = 0; counter < positive_integer; counter++)
SHOW counter
IF (counter >= 5) THEN
ENDIF
ENDFOR
Code for the Break Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a break statement
#include <stdio.h>
int main() {
// this function uses a break statement
int positiveInteger;
// input
printf("Enter how many times to repeat: ");
scanf("%d", &positiveInteger);
printf("\n");
// process & output
for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
printf("%d time(s) through the loop.\n", loopCounter);
if (loopCounter >= 5) {
break;
}
}
printf("\nDone.\n");
return 0;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | // Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a break statement
#include <iostream>
int main() {
// this function uses a break statement
int positiveInteger;
// input
std::cout << "Enter how many times to repeat: ";
std::cin >> positiveInteger;
std::cout << std::endl;
// process & output
for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
std::cout << loopCounter <<" time through loop." << std::endl;
if (loopCounter >= 5) {
break;
}
}
std::cout << "\nDone." << std::endl;
return 0;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a break statement
*/
using System;
/*
* The Program class
*/
class Program {
static void Main() {
// this function uses a break statement
int positiveInteger;
// input
Console.Write("Enter how many times to repeat: ");
positiveInteger = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
// process & output
for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
Console.WriteLine(loopCounter + " time(s) through the loop.");
if (loopCounter >= 5) {
break;
}
}
Console.WriteLine("\nDone.");
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a break statement
*/
package main
import (
"fmt"
)
func main() {
// this function uses a break statement
var counter int // in go no need to set to 0, it automaticall is!
var positiveInteger int
// input
fmt.Print("Enter how many times to repeat: ")
fmt.Scan(&positiveInteger)
fmt.Println()
// process & output
for counter < positiveInteger {
fmt.Printf("%d time(s) through the loop.\n", counter)
if counter >= 5 {
break
}
counter++
}
fmt.Println("\nDone.")
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 | /*
* This program uses a break statement
*
* @author Mr Coxall
* @version 1.0
* @since 2020-09-01
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// this function uses a break statement
// create Scanner object for user input
Scanner scanner = new Scanner(System.in);
// input
System.out.print("Enter how many times to repeat: ");
String positiveIntegerStr = scanner.nextLine();
System.out.println();
// process & output
int positiveInteger = Integer.parseInt(positiveIntegerStr);
for (int loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
System.out.println("%d time(s) through the loop.".formatted(loopCounter));
if (loopCounter >= 5) {
break;
}
}
// close the Scanner object
scanner.close();
System.out.println("\nDone.");
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a break statement
*/
const prompt = require("prompt-sync")()
let counter = 0
// input
const positiveIntegerStr = prompt("Enter how many times to repeat: ")
console.log("")
// process & output
const positiveInteger = parseInt(positiveIntegerStr)
for (var loopCounter = 0; loopCounter < positiveInteger; loopCounter++) {
console.log(`${loopCounter} time(s) through the loop.`)
if (loopCounter >= 5){
break
}
}
console.log("\nDone.")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 | #!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses a break statement
"""
def main() -> None:
"""The main() function uses a break statement, returns None."""
# input
positive_integer = int(input("Enter how many times to repeat: "))
print("")
# process & output
for loop_counter in range(positive_integer):
print(f"{loop_counter} time through loop.")
if loop_counter >= 5:
break
print("\nDone.")
if __name__ == "__main__":
main()
|
Example Output