Lets Understand for loop with break and continue

Lets see how for loop work.
for(int i=0;i<10;i++) this is for loop, this will start for 0 to 10 (these are boundary condition start-end)
so start - int i=0, end i<10  so this loop will start from 0 and it will end to 9 because we are using i<10 here if we will use i<=10 so it will run till 10, and i++ is increasing value of i each time.

so :
Exp1 - for(int i=0;i<10;i++){
                   System.out.println(i);
               }

This will print 0-9, we can change this loop to infinite loop just removing second boundary condition,
Exp2 - for(int i=0;;i++){
               System.out.println(i);
            }

This will keep increasing the value of i and will keep printing so its in infinite loop now.

Or we can change this to :

Exp3 - for(int i=0;;){
                System.out.println(i);
                i++;
            }

Both are same exp3 & exp2. or else we can use i+=1 to increment value of i.

If we want to break a for loop at some condition or at some value of i so we can use below code.

Exp4 : for(int i=0;i<5;){
if(i==2)break;
System.out.println(i);
i +=1;
}

This will print till 1(0,1) then it will come to 2 where i==2 then break so it will come out from the loop.

Exp4 : for(int i=0;i<5;i++){
if(i==3){
continue;
}
System.out.println(i);
}

In exp4 we are using continue  so when i will become 3 it will go back to starting of loop and will not go below the if so it will not print 3, so it will print 0,1,2,4.

Exp5 : for(;;){
System.out.println(1);
}

Exp5 is also an infinite loop its don't have any start condition and no end condition so it will keep running and keep printing 1 each time.
           



             





Post a Comment

Previous Post Next Post