Loop Construct – Break
The break
statement is a control flow statement in programming languages that allows you to terminate a loop prematurely and exit the loop block, without executing the remaining statements in the loop.
The break
statement is commonly used inside loops that iterate over a sequence of values, such as the for
and while
loops. When the break
statement is encountered inside a loop, the program immediately exits the loop block, and control is transferred to the statement immediately following the loop.
Here is an example of using the break
statement in C to search for a value in an array and terminate the loop when the value is found:
int numbers[] = {1, 2, 3, 4, 5};
int searchValue = 3;
int i;
for (i = 0; i < 5; i++) {
if (numbers[i] == searchValue) {
printf("Value found at index %d\n", i);
break;
}
}
In this example, the for
loop iterates over each element in the numbers
array, and the if
statement checks if the current element is equal to the searchValue
. If the element is equal to the searchValue
, the printf
statement is executed, and the loop is terminated using the break
statement. If the searchValue
is not found in the array, the loop continues until all elements have been checked.
The break
statement can be useful for terminating loops early when a certain condition is met, and for simplifying complex loop logic. However, it should be used with caution, as excessive use of break
statements can make the code harder to read and understand.
Apply for PHP Certification!
https://www.vskills.in/certification/certified-php-developer