Home / Programs / break statement in while loop
Programming Example

break statement in while loop

👁 1,313 Views
💻 Practical Program
📘 Step by Step Learning
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.

Program Code

#include <stdio.h>
void main ()
{ 
int a =  0 ; 
while( a < 100 )
{
	printf("value of a: %d\n", a);
	a++;
	if( a == 50 )
	{ 
	 break;
	}
 }
 
}

Output

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 . . .

Explanation

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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.