-5

If i write break statement in for loop then will variable be updated and then for loop exits,or after just excecution of break statement for loop exits? for e.g

for(i=0;i<100;i++){
//do something something
if(i==50){
break;
}  

what will be the value of i after for loop exit?

shafeeq
  • 141
  • 1
  • 3
  • 14

3 Answers3

5

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.It can be used to terminate a case in the switch statement

enter image description here

Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
4

The value will be 50.

The for loop can be described in general terms like this:

for(INIT; CONDITION; UPDATE)
  BODY

and it can be replaced with the equivalent while loop, like this:

INIT
while(CONDITION)
{
  BODY
  UPDATE
}

So, since your break is in the BODY, the UPDATE is not run, and the value 50 remains.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

If loop ready to exit by the break statement , that mean the i value should be equal to the condition .

if(i==50);

i Will be 50

...

Kumar KL
  • 15,315
  • 9
  • 38
  • 60