The break keyword is used to terminate a loop, immediately bypassing any conditions. The control will be transferred to the first statement following the loop block. If you have nested loops, then the break statement inside one loop transfers the control to the immediate outer loop. The break statement can be used to terminate an infinite loop or to force a loop to end before its normal termination.
Consider the following example:
/* Program-5.7 */
#include <stdio.h>
int main()
{
int n;
for(n=10;n>0;n--)
{
printf("Hello World!\n");
if(n == 5)
{
printf("Countdown aborted!");
break;
}
}
return 0;
}
Under normal circumstances the Program-5.7 will display the “Hello World!” message 10 times. Notice that in this example the for loop is written as a decrement rather than an increment. During the first 5 iterations the program executes normally displaying the message “Hello World!”. Then at the beginning of the sixth iteration variable “n” becomes “5”. Therefore the if condition which evaluates whether “n==5” becomes TRUE, so it will execute the printf function and then the break instruction. At this point the loop will terminate because of the break keyword.
No comments:
Post a Comment