Summary: in this tutorial, you will learn how to use the C break statement to exit a loop, including for loop, while loop, and do. while loop.
The break statement allows you to exit a loop early than usual. Typically, you’ll use the break statement in a for loop, while loop, or do. while loop.
The break statement includes the break keyword followed by a semiconlon ( ; ) like this:
Code language: C++ (cpp)break;
In practice, you often use the break statement with an if statement to specify the condition to exit the loop. It’ll look like this:
Code language: C++ (cpp)// somewhere inside a loop if(expression) break;
In this syntax, if the expression is non-zero (or true ), the break statement will exit the loop.
Note that you can use the break statement inside a case statement of the switch. case statement. However, this tutorial focuses on how to use the break statement inside a loop.
The following example illustrates how to use the break statement inside a for loop:
Code language: C++ (cpp)#include int main() < int i; for (i = 0; i < 10; i++) < if (i == 5) break; printf("%d ", i); > >
0 1 2 3 4
The for loop is supposed to execute 10 times. However, when i reaches 5 , the break statement immediately terminates the loop. Therefore, the loop runs only 5 times.
The following example shows how to use the break statement inside a do. while loop:
Code language: C++ (cpp)#include int main() < char key; printf("Type something (q to quit): "); do < scanf("%c", &key); if (key == 'Q' || key == 'q') break; > while (1); >
The condition in the do…while loop is 1. Therefore, the do. while loop will execute repeatedly until it encouters a break statement.
The program prompts for a character:
Code language: C++ (cpp)scanf("%c", &key);
If you type the letter q or Q , the break statement will terminate the loop immediately:
Code language: C++ (cpp)if (key == 'Q' || key == 'q') break;
The following example illustrates how to use the break statement inside a while loop:
Code language: C++ (cpp)#include int main() < int n, total = 0; printf("Enter a positive number (0 or negative to exit):"); while (1) < scanf("%d", &n); if (n 0) break; total += n; > printf("The total is %d", total); >
Like the above example, the while(1) will run its body until it encounters a break statement.
Inside the loop, prompt users for a positive integer:
Code language: C++ (cpp)scanf("%d", &n);
If the input number is less than or equal to zero, the break statement ends the loop:
Code language: C++ (cpp)if (n 0) break;
However, if the input number is greater than zero, the program adds it to the total:
Code language: C++ (cpp)total += n;
Once the while loop ends, show the total of entered numbers:
Code language: C++ (cpp)printf("The total is %d", total);