break statement

The break statement is used to break any type of loop such as while loop, do – while loop, for loop or switch statement. break statement terminate the loop body immediately.

When break is encountered inside any loop control automatically passes to the first statement after the loop.

We see the first program of for() loop, where we are printing 0 to 10 numbers on display. Now we do not want to print numbers greater than 5 then what to do..?  Just use break  statement whenever value of variable becomes qual to 5, see below.

#include<stdio.h>
int main()
{

int count;for (count = 0; count <= 10; count++)

{

if (count > 5)

{

break;

}

printf(“%d \t”,count);

}

return 0;

}

Explanation :-
In above C program the if statement will be true when value of count becomes equal to 5,  and compiler encounters with break statement, whenever break is encountered inside any loop control automatically passes to the first statement after the loop, the output is :-
$  ./a.out
0    1    2    3    4    5

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.