Friday, November 25, 2011

Exiting from Nested Loops in Java

Let us consider a program that takes as input 5 numbers and outputs their sum.The program should do this thing 20 times. He should also only close immediately after the user entered 100 numbers (5 numbers x 20 times) or if the user introduces 0 as one of the numbers.

To implement such a program, nested loops are needed: one loop to ensure that the program keeps running 20 times (called a outer loop) and another loop (called an inner loop) where the user is asked 5 times for his input. The problem arises when the user inputs 0. Using the "normal" break statement, one could prematurely close the inner loop but it would exit to the outer loop and would not end the program (but rather restart the input process)

There are two ways to solve this problem:

1.Introducing a boolean flag in the loop's invariant

By introducing a boolean variable (a flag) to the loop's invariant we make sure that for each iteration of the outer loop it is checked if the program encountered 0 as user input. If the program encounters 0 it will change the state of the boolean variable and it will cause the outer loop to end (the inner loop will be exited through a break statement).

Also, before outputting the sum, for each iteration one needs to check also if the boolean variable was set or not (the program encountered 0 or not). Otherwise, the program will output the sum even if 0 was encountered.
  boolean exitFlag = false;
  int counter = 0;
  int i=0, temp=0;
  int sum = 0;
  Scanner keyboard = new Scanner(System.in);
  while(exitFlag==false && counter!=20)
  {
   System.out.println("Input five numbers: ");
   for(i=0;i<5;i++)
   {
    temp = keyboard.nextInt();
    if(temp!=0)
     sum += temp;
    else
    {
     exitFlag = true; //ExitFlag
     break;
    }
   }
   if(exitFlag==false)
        System.out.println("The sum of the last 5 numbers is:"+sum);
   sum=0;
   counter++;
  }

2.Using an identifier for the break statement

The main advantage of this method is that is less complex that the previous one and it consumes less execution time. Of course, considering the example program, execution time is not an important problem but in some other cases it may prove crucial (especially when it comes to real-time systems or multithreading applications)

By using an identifier/label (outerloop), one can use a labelled break statement in order to directly exit a loop specified by its label. This way, the outer loop's invariant is simplified (there is no need to check for a boolean flag) and the sum outputting process can also go unchecked. Some may argue that this method is reminiscent of C's goto and leads to a bad programming style, but sometimes it may prove quite handy.
  int i=0, temp=0;
  int counter = 0;
  int sum = 0;
  Scanner keyboard = new Scanner(System.in);
  outerloop:    //Label
   while(counter!=20)
   {
    System.out.println("Input five numbers: ");
    for(i=0;i<5;i++)
    {
     temp = keyboard.nextInt();
     if(temp!=0)
      sum += temp;
     else
      break outerloop; //Labeled break
    }
    System.out.println("The sum of the last 5 numbers is:"+sum);
    sum=0;
    counter++;
   }

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger