Thursday, 6 September 2018

How to break outer loop in Java?

Given below function, Interviewer wants me to break the outer loop.

         private static void print() {
                  for (int i = 0; i < 10; i++) {
                           for (int j = 0; j < 10; j++) {
                                    System.out.println(i + " " + j);
                                    if (i * j > 10) {
                                             break;
                                    }
                           }
                  }
         }

There are couple of ways to do this.

Way 1: Use a flag to come out of outer loop

Application.java
package com.sample.app;

public class Application {

 private static void print() {
  boolean flag = false;
  for (int i = 0; i < 10; i++) {
   for (int j = 0; j < 10; j++) {
    System.out.println(i + " " + j);
    if (i * j > 10) {
     flag = true;
     break;
    }
   }

   // Breaking outer loop
   if (flag)
    break;
  }
 }

 public static void main(String args[]) {
  print();
 }
}

Way 2: You can use labels to come out of outerloop.

Application.java
package com.sample.app;

public class Application {

 private static void print() {
  outerLoop: for (int i = 0; i < 10; i++) {
   for (int j = 0; j < 10; j++) {
    System.out.println(i + " " + j);
    if (i * j > 10) {
     break outerLoop;
    }
   }
  }
 }

 public static void main(String args[]) {
  print();
 }
}

You may like

No comments:

Post a Comment