We have seen that a break statement is usually used in a switch statement after the statements in each case. The execution of such a break statement causes the execution of the switch statement to be terminated and the control to be transferred to the statement following the switch statement.
C also allows the break statement to interrupt the execution of a loop and transfer the control to the statement following that loop. The format of this statement is
It is obvious that within a loop, the break statement must be used in an if statement to transfer the control outside the loop only when a specified condition is satisfied; otherwise, the looping action will not take place.
The break statement terminates the execution of the nearest enclosing for, while, do or switch statement in which it appears. Thus, if we use the break statement within nested loops, its execution causes the control to leave the innermost loop in which it is contained.
Note that the compiler will report an error if the break statement is encountered outside a switch or looping construct.
Using the break statement within loops
Consider the program segment given below that determines the sum of n given numbers until a desired value max sum is attained or all the numbers are exhausted:
sum = 0;
for (i = 0; i < n; i++)
sum += num;
if (sum >= max_sum)
The for loop is set up to determine the sum of n numbers entered from the keyboard. However, if a specified max_sum is attained, the execution of the loop is interrupted using a break statement.
Now let us print the result that includes the final value of sum and count of numbers required to attain this sum. This can be done inside the if statement in the above code. However, if the desired sum is not attained even after processing all the numbers, the result will not be printed. Thus, it is appropriate to print this result after the for loop using a printf statement as shown below.
printf("Sum = %d count= %d\n", sum, ??); /*replace?? By count expr */
However, the problem here is in printing the count of numbers actually processed as indicated by ?? in the above statement. Observe that if max_sum is attained, the control will surely leave the loop via the break statement and the desired count is equal to i +1; otherwise, the control leaves the loop after n iterations are over, in which case, the desired count will be equal to either n or i. Thus, we can write the above pr intf statement using a conditional operator (?:) as shown below:
printf("Sum = %d count= %d\n", sum, (sum>= max_num? i + 1: n));
Now assume that we wish to improve the result to indicate whether the desired max_sum was attained or not. This can be done using an if-else statement after the loop:
if (sum < max_sum)
printf("Max sum not attained. Sum= %d count= %d\n", sum, n);
else printf("Max sum attained. Sum= %d count= %d\n", sum, i + l);