Exit from nested for loops in java

There are 2 nested for loops in your code and if we want to exit both the loops at a time once a particular condition satisfies.
If we write break once the condition satisfies, control exits from inner for loop, but main for loop runs as usual, we want to basically exit this main loop as well.

Lets see the code implementation:


We will be searching a number in an array (2 dim), if found in that array, then stop searching and come out of both the loops.

package testPkg;

public class Nestedloop {

public static void main(String[] args) {
 
    int arr[][] = new int[][]{{2,4},{6,8},{10,12}};
    //Java understands automatically size of array
    boolean flag = false;
    mainLoop: //A statement, will use in inner for loop later
    for(int i=0;i<arr.length;i++)
       {
          for(int j=0;j<arr[i].length;j++)
          {
             if (arr[i][j] == 6)
             {
                flag = true;
                break mainLoop; //break from the line, where written statement mainloop:
             }
          }
       }
       if (flag)
          System.out.println("Found");
       else
          System.out.println("Not Found");
   }
}

No comments:

Post a Comment