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

Local Variables and its Scope

What is an algorithm?

An algorithm is a set of code statements that you write as a program to solve a computational problem. All the solutions that you have written in various exercises construe as an algorithm. In other words, Algorithms are precise sequences of instructions that can be executed by the computer. Once an algorithm is written, the computer executes it the exact same way every time it is run. A typical algorithm consists of using many logical constructs, which includes loops, conditionals and statements.

The algorithm adopted by one student may be different from the algorithm 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 most efficient algorithm would be the one:

  • 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. Different correct algorithms for the same problem can have different efficiencies.

Many a times the most efficient algorithm is complex and hard to understand. However, you may have to sacrifice efficiency a little to make the code easy to understand, because, 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!

What is Pseudocode?

Before you write the real code, you may have instances when you want to explain your algorithm to someone or you may want to just scribble out the steps that your algorithm should take. This informal high-level description of your algorithm which is human readable but not computer readable is called Pseudocode. Pseudocodes are typically programming language agnostic and just represent the algorithm in human readable statements using generic computing constructs.

Programming Challenge

Write a program to add all numbers from 1 to 'n' where 'n' can be set to any number from the Scanner input.

Pseudocode

The first step is to generate all the numbers from 1 to n, which you already know; by using some type of loop.

You may use a piece of paper to job down these thoughts when you are thinking through.

Let us assume the input number is 10 then the numbers that we need to generate and add are 1,2,3,4,5,6,7,8,9,10

Next add all the numbers sum= 1+2+3+4...+10

You already know how to generate these numbers. Using some loop of course!

Now let us start writing the real code!..


class NumbersAdder {

    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++){
            System.out.println(i);
        }
    }
}

Now that you generated those numbers, you have to create some statements to add those numbers. How do you do that?

An algorithm to solve this problem can be written in many different ways. Let us write one way of solving them. Let us declare another variable called sum and initialize it to '0'.

sum = 0;

To this variable we want to add all the values of 'i' that is generated in the loop. So basically take the value of sum and add the value of i at every iteration. That expression would be:

sum = sum + i;

When the loop finally finishes, you have the total in the sum variable. Let us finish this problem now:


class NumbersAdder {

    public static void main(String[] args) {
        int sum = 0;
        for (int i = 0; i <= 10; i++){
            sum = sum + i;
        }
        System.out.println(sum);
    }
}

Now the questions:

  • Why did we declare the sum variable outside of the for loop?
  • If you keep the sum variable inside of the for loop what happens?
  • If you have the System.out.println statement inside of the for loop what happens?

Nested blocks

So far we saw simple loops and conditional blocks. However nothing stops you from using a loop inside of a if-block and vice-versa. Here is an example:


class NumbersAdder {

    public static void main(String[] args) {
        int sum = 0;
        for (int i = 0; i <= 10; i++){
            if (i != 5){
                sum = sum + i;
            }
        }
        System.out.println(sum);
    }
}

In the above code block, number '5' is not added. When 'i' has a value other than 5 then you add otherwise not.

While the above example is an 'if' block inside a 'for' loop. You can also have a loop inside a conditional and in fact you can have any level of nesting of this sort.

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 ':'

results matching ""

    No results matching ""