Programming Example
break statement in while loop
The break statement has two uses. You can use it to terminate a case in the switch statement
(covered in the section on switch earlier in this chapter). You can also use it to force immediate
termination of a loop, bypassing the normal loop conditional test.
When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop.
#include <stdio.h>
void main ()
{
int a = 0 ;
while( a < 100 )
{
printf("value of a: %d\n", a);
a++;
if( a == 50 )
{
break;
}
}
}
value of a: 0
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
value of a: 21
value of a: 22
value of a: 23
value of a: 24
value of a: 25
value of a: 26
value of a: 27
value of a: 28
value of a: 29
value of a: 30
value of a: 31
value of a: 32
value of a: 33
value of a: 34
value of a: 35
value of a: 36
value of a: 37
value of a: 38
value of a: 39
value of a: 40
value of a: 41
value of a: 42
value of a: 43
value of a: 44
value of a: 45
value of a: 46
value of a: 47
value of a: 48
value of a: 49
Press any key to continue . . .
This will print from o to 49 then break will take place.When the break statement is encountered inside a loop, the loop is immediately terminated, and
program control resumes at the next statement following the loop.