Loops

Loops are a type of control structure that allows you to repeat a certain number of statements a certain number of times. Here are the loop types in Java.

The while Loop:

The syntax of a while loop is:

while (boolean_expression){
  //Statements
}

During executing, if the boolean_expression result is true, then the statements inside the loop will be executed. This will continue as long as the boolean expression result is true. When the boolean expression is false, the loop statements will be skipped and the first statement after the while loop will be executed.

Example:

public class WhileLoopDemo {

   public static void main(String args[]) {
      int x = 10;

      while( x < 20 ) {
         System.out.println("value of x : " + x );
         x++;
      }
   }
}

Check the result.

What happens if you do not add x++; statement in the above code?

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

The syntax of a do...while loop is:

do {
  //Statements
} while (boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the boolean expression is tested. If the boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the boolean expression turns to false.

Example:

public class DoWhileLoopDemo {

   public static void main(String args[]) {
      int x = 10;

      do {
         System.out.println("value of x : " + x );
         x++;
      } while( x < 20 );
   }
}

Check the results.

What is the difference in the execution between the while and do-while in the above example?

The for Loop:

for loops is similar to while and do while except the for construct not only takes in conditional expression but also an initialization block and update block.

The syntax of a for loop is:

for(initialization; boolean_expression; update){
  //Statements
}

Here is the flow of control in a for loop:

  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. If you do not need an initialization block, you can skip it but should put in a semicolon anyways.
  • Next, the boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  • After completing the update statement, the boolean expression is evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then boolean expression). Once the boolean expression is false, the for loop terminates.

Example:

public class ForLoopDemo {

   public static void main(String args[]) {

      for(int x = 10; x < 20; x++) {
         System.out.println("value of x : " + x );
      }
   }
}

Check the results

Break and Continue statements

The break keyword in loops:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the loop and start executing the next line of code after the loop block. In case of nested loops, break statement will stop the execution of the innermost loop where the break is present. Outer loops are unaffected.

Syntax: The syntax of a break is a single statement inside any loop:

break; Example:

public class BreakExample {

   public static void main(String args[]) {

     for(int x = 10; x < 20; x++) {
         if( x == 15 ) {
             break;
         }
         System.out.println("value of x : " + x );
     }

   }
}

Check the result. What do you notice? Why did the display stop at number 15?

The continue keyword in loops:

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop:

continue; Example:

public class ContinueExample {

   public static void main(String args[]) {

     for(int x = 10; x < 20; x++) {
         if( x == 15 ) {
             continue;
         }
         System.out.println("value of x : " + x );
     }

   }
}

Check the results. What do you notice? Why is number 15 missing in the print statement?

Nested loops

A loop can be inside another loop. For e.g., a for loop can be inside a while loop etc.. When there is a break or a continue statement inside the a loop, then the keyword is applied to the first loop which encloses the keyword. For e.g., in the below example, the conditional break is applied to the inner loop.


class NestedLoops {
   public static void main(String[] args) {

      for (int i = 1; i <= 20; i++) {
         System.out.println("Outer loop iteration " + i);
         for (int j = 1; j <= 15; j++) {
            System.out.println("Inner loop iteration " + j);
            if(j % 5 == 0 )
                break;
         }
      }
   }
}

When the conditional j % 5 is reached then the inner loop is terminated and the program of execution jumps to the next iteration of the outer loop.

Use of Label If you want to break the outer loop instead of the inner loop in the above program, you would use a label statement to label the outer loop and use the label name in the break statement. Here is an example:


class NestedLoops {
   public static void main(String[] args) {

      outer:
      for (int i = 1; i <= 20; i++) {
         System.out.println("Outer loop iteration " + i);
         for (int j = 1; j <= 15; j++) {
            System.out.println("Inner loop iteration " + j);
            if(j % 5 == 0 )
                break outer;
         }
      }
   }
}

Note that after the break you have the label outer and that label is defined for the outer loop just above the loop with the same name. This is also an identifier so you can give any identifier literal for the label. But be sure to end it with a colon (:)

What is an algorithm?

An algorithm is a set of code statements that you write as a program to solve a problem. All the solutions that you have written in various exercises construe as an algorithm.

The procedure adopted by one student may be different from the procedure adopted by another student to solve the same problem. Each student typically comes up with their own unique algorithm to solve the same problem.

The best algorithm would be the one:

  • where code is easy to understand for anyone
  • which uses fewer statements (a.k.a. lines of code)
  • which uses fewer resources

Resources are nothing but the amount of CPU time that is used and the amount of RAM that is used to solve a problem. CPU time used is directly proportional to the number of statements that are used in the program. And RAM usage is directly proportional to the amount and type of variables that are used in the program to hold the data.

However, remember that some times you may have to sacrifice performance a little to make the code easy to understand as simple and elegant code trumps over a small loss in performance.

How to write a great algorithm?

Just like an artist drawing a great painting takes many tries, getting a great algorithm also takes several attempts. Even experienced programmers will have a very difficult time coming up with a great algorithm for moderately complex problems in their first try! Getting a great algorithm takes patience, perseverance and grit to excel!

You start with thinking through the problem and coming up with your first draft of your solution which works. Getting it working as per the requirement should be your first goal. Once you have the solution, analyze every statement, variable and logic to see if you can make it better. If you find areas of improvement, make the changes and ensure that your program still meets the requirement. Having a testcase which tests the requirement would definitely help. However writing tests is beyond the scope of this book.

You might have to scan through your code multiple times and make multiple changes before you get a great algorithm!

results matching ""

    No results matching ""