A loop control statement utilized to terminate a loop in C++ is referred to as a break. The loop iterations come to a halt upon encountering the break statement within the loop, facilitating an immediate transfer of control to the initial statement following the loop.
break; //syntax
Break statements are commonly employed in situations where the exact number of loop iterations is uncertain or when it is necessary to terminate the loop based on a specific condition.
Here, we'll explore how to use three distinct loop types with break statements:
- Simple loops
- Nested loops
- Infinite loops
Now, let's explore the examples that utilize the break statement for each of the three loop variations discussed earlier.
Break with Simple loops
Think of a situation where a specific item needs to be located within an array. Employ a loop to sequentially go through the array, starting from the initial index, and subsequently match each array element with the given key to achieve this task.
Example:
// C++ program to illustrate
// Linear Search
#include <iostream>
using namespace std;
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
cout << "Element found at position: " << (i + 1);
}
}
}
// Driver program to test above function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = 6; // no of elements
int key = 3; // key to be searched
// Calling function to find the key
findElement(arr, n, key);
return 0;
}
OUTPUT:
Element found at position: 3
……………………………………………
Process executed in 1.11 seconds
Press any key to continue.
Explanation
The specified code runs smoothly without any issues. Nevertheless, the specified code proves to be inefficient. Even if the element is found early on, the specified code will still iterate through all elements. In a scenario where the array holds 1000 elements and the target key is found at the beginning, this method will needlessly execute 999 additional iterations.
We can make use of the break statement in our software to halt unnecessary iterations. Exiting the loop immediately upon encountering the break statement allows for efficient control flow. Therefore, in the example below, we will integrate the break statement with an if condition that checks the key against array elements:
Example:
// C++ program to illustrate
// using break statement
// in Linear Search
#include <iostream>
using namespace std;
void findElement(int arr[], int size, int key)
{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
cout << "Element found at position: "
<< (i + 1);
// using break to terminate loop execution
break;
}
}
}
// Driver program to test above function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
int n = 6;
// key to be searched
int key = 3;
// Calling function to find the key
findElement(arr, n, key);
return 0;
}
OUTPUT:
Element found at position: 3
..................................................
Process executed in 1.11 seconds
Press any key to continue.
Break with Nested Loops
When dealing with nested loops, break statements can be used as an alternative when the break statement is present in the innermost loop. Only the innermost loop will be exited by the break statement.
// C++ program to illustrate
// using break statement
// in Nested loops
#include <iostream>
using namespace std;
int main()
{
// nested for loops with break statement
// at inner loop
for (int i = 0; i < 5; i++) {
for (int j = 1; j <= 10; j++) {
if (j > 3)
break;
else
cout << "*";
}
cout << endl;
}
return 0;
}
OUTPUT:
***
***
***
***
***
……………………..
Process executed in 1.11 seconds
Press any key to continue.
Explanation
We observe in the provided code that the inner loop is configured to execute for 10 cycles. However, the inner loop terminates once the variable j exceeds 3, constraining the inner loop's cycles to only 3. Conversely, the progress of the outer loop remains unaffected. Therefore, the break statement exclusively influences the loop within which it is situated.
Break with Infinite Loops
To terminate an infinite loop, the break statement can be employed along with a specific condition.
Example:
// C++ program to illustrate
// using break statement
// in Infinite loops
#include <iostream>
using namespace std;
int main()
{
// loop initialization expression
int i = 0;
// infinite while loop
while (1) {
cout << i << " ";
i++;
}
return 0;
}
OUTPUT:
Execution timed out
..................................
Process executed in 1.11 seconds
Press any key to continue.
Explanation
The loop condition in the mentioned program, which specifies when to terminate the loop, is constantly evaluated as true. As a result, the loop continues to execute endlessly.
NOTE: Please refrain from running the aforementioned program in your compiler since it is in an indefinite loop and will likely require you to forcibly quit the compiler in order to end the program.
By utilizing the break statement, as illustrated below, we can address this issue:
// C++ program to illustrate
// using break statement
// in Infinite loops
#include <iostream>
using namespace std;
int main()
{
// loop initialization expression
int i = 1;
// infinite while loop
while (1) {
if (i > 10)
break;
cout << i << " ";
i++;
}
return 0;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10
................................
Process executed in 1.11 seconds
Press any key to continue.
Explanation
The specified code restricts the number of loop iterations to ten. Additionally, the break statement can be utilized within Switch case statements.
Continue statement in C
The continue statement in C languages functions as a control statement that directs the program flow back to the loop's beginning. It is applicable in while loops, for loops, and do-while loops, offering a means to alter the default program execution. Unlike the break statement, the continue statement is not compatible with C switch cases.
When employed, the C continue statement transfers control back to the beginning of the loop. Consequently, the iteration proceeds to the next cycle, bypassing the current one. Any statements within the loop that come after the continue statement are not executed.
Just inserting the continue keyword at any desired location within the loop body constitutes the continue syntax.
continue; //syntax
Use of continue in C
Each variant of loop in C has the capability to bypass the ongoing iteration by utilizing the continue keyword. This functionality can be employed with the subsequent categories of loops in C:
- Individual Loops
- Loops within Loops
Utilizing the continue statement within infinite loops is not beneficial because bypassing the current iteration does not impact the outcome when the loop runs indefinitely.
Example of continue in C
Example 1: A program that employs a singular loop along with the continue statement.
The continue statement is compatible with the for, while, and do-while loops.
// C program to explain the use
// of continue statement with for loop
#include <stdio.h>
int main()
{
// for loop to print 1 to 8
for (int i = 1; i <= 8; i++) {
// when i = 4, the iteration will be skipped and for
// will not be printed
if (i == 4) {
continue;
}
printf("%d ", i);
}
printf("\n");
int i = 0;
// while loop to print 1 to 8
while (i < 8) {
// when i = 4, the iteration will be skipped and for
// will not be printed
i++;
if (i == 4) {
continue;
}
printf("%d ", i);
}
return 0;
}
OUTPUT:
1 2 3 5 6 7 8
1 2 3 5 6 7 8
.........................
Process executed in 1. 11 seconds
Press any key to continue.
A program that employs nested loops carries on in the C programming language.
The continue statement can handle one loop at a time. When working with nested loops, we can use the continue statement to skip the current iteration of the inner loop.
// C program to explain the use
// of continue statement with nested loops
#include <stdio.h>
int main()
{
// outer loop with 3 iterations
for (int i = 1; i <= 3; i++) {
// inner loop to print integer 1 to 4
for (int j = 0; j <= 4; j++) {
// continue to skip printing number 3
if (j == 3) {
continue;
}
printf("%d ", j);
}
printf("\n");
}
return 0;
}
OUTPUT:
0 1 2 4
0 1 2 4
0 1 2 4
.............
Process executed in 1.11 seconds
Press any key to continue.
Explanation
When the continue statement is implemented in the code snippet mentioned, it bypasses the ongoing iteration of the inner loop. Consequently, the inner loop's update expression controls the program flow, ensuring that the number 3 is never displayed in the output in this manner.
The continue statement operates as follows:
- STEP 1: After determining that the loop condition is true, the loop begins to run.
- STEP 2: The continue statement's condition will be assessed.
- STEP 3A: If the condition is untrue, the execution will proceed as usual.
- STEP 3B: If the condition is met, the program will move to the beginning of the loop and skip everything that comes after the continue statement.
- STEP 4: Up until the loop's conclusion, steps 1 through 4 will be repeated.
Even though both break and continue statements interrupt the normal execution flow of a program, they possess distinct characteristics that set them apart from each other.
With the break statement, the smallest enclosing loop is ended (i. e., while, do-while, for or switch statement)
Continue: The continue statement skips the remaining loop statements and starts the loop's subsequent iteration.
An example showcasing the contrast between a break and continue statement.
// CPP program to demonstrate difference between
// continue and break
#include <iostream>
using namespace std;
main()
{
int i;
cout << "The loop with break produces output as: \n";
for (i = 1; i <= 5; i++) {
// Program comes out of loop when
// i becomes multiple of 3.
if ((i % 3) == 0)
break;
else
cout << i << " ";
}
cout << "\nThe loop with continue produces output as: \n";
for (i = 1; i <= 5; i++) {
// The loop prints all values except
// those that are multiple of 3.
if ((i % 3) == 0)
continue;
cout << i << " ";
}
}
OUTPUT:
The loop with break produces output as:
1 2
The loop with continue produces output as:
1 2 4 5
……………………………………………………………………..
Process executed in 0.1 seconds
Press any key to continue.
Explanation:
In the code snippet provided, the initial loop is designed to showcase the variable I's value until it reaches 3, at which point it terminates due to the presence of a break statement to halt execution. Consequently, when I reaches 3, the subsequent for loop proceeds without displaying the output for I.