Showing posts with label Control Flow. Show all posts
Showing posts with label Control Flow. Show all posts

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++;
   }

Thursday, November 24, 2011

Short Circuit Evaluation

Short circuit evaluation (also called "lazy" evaluation or McCarthy Evaluation) is a commonly used method for avoiding the execution of a second expression contained in a conditional clause.

Speaking plainly, it means that when you use an if instruction that has 2 or more clauses, if the first condition is not met (when the conditions are connected by an AND operator) or if the first condition is met (when the conditions are connected by an OR operator), the program will not evaluate the second expression.

The short circuit evaluation is available for C, C++, Java, C# and VB (and most of the other programming languages. See this for the full list). 

It is commonly used for:
  • Checking before a division that the denominator is not equal to 0
  • Checking if a pointer is allocated before doing some operation with the data that he is pointing to.
Also, short circuit evaluation helps optimizing the code since an if statement that contains 5 clauses will end very quickly if one condition is not respected (without continuing to evaluate the other clauses), so your program will run more quickly.

Division check example for C\C++, Java and C#:
int a = 0, b = 32;
if ( (a != 0) && (b / a > 10) )
   //Will not go here because a=0
else
   //Will go here without triggering an divide by zero error/exception
Division check example for VB.NET
Dim x, y As Integer
x = 0
y = 32
If ( (x <> 0) AndAlso (x / y > 10) ) Then
   'Will not go here because x=0
Else
   'Will go here without triggering an division by zero exception
End If
Pointer example for C\C++
//We shall assume that you have a structure/class with a field
//(a public field in//case of C++) data.
MyStruct *myStructPointer = NULL;
if ( (myStructPointer!=null) && (myStructPointer.data == 5) )
   //Will not go here because myStructPointer = null
else
   //Will go here without triggering a null error/exception
Pointer (Reference) example for Java and C#
//We shall assume that you have a class containing
//a public field called data.
Xobject myObject = null;
if ( (myObject!=null) && (myObject.data == 5) )
   //Will not go here because myObject = null
else
   //Will go here without triggering a null error/exception
Pointer (Reference) example for VB. NET
If ( (str <> Nothing) AndAlso (str.Equals("Bird") ) Then
   'Will not go here because x=0
Else
   'Will go here without triggering a null exception
End If
In VB.NET the short circuit OR operator is OrAlso.

In some cases you may not want to use short circuit evaluation, but rather let the program evaluate all clauses. In this case you will need to use "eager" operators like (in contrast to the "lazy" operators used in short circuit evaluation):
  • C++\C#\Java : & instead of && and | instead of ||
  • Java has also : and instead of && and or instead of ||
  • VB.NET : and instead of andAlso and or instead of orAlso 
  • C doesn't have "eager" operators and all evaluation is done short-circuit only.
"Eager" operators are mostly used when your second condition consists of a function that modifies some of your other variables (but this corresponds in most cases to a bad programming style).
Related Posts Plugin for WordPress, Blogger...