Skip to content

Loops

In programming, loops are used to execute a specific code block repeatedly until a particular condition is met. Automation engineers use loops to perform similar test verifications over an over without having to write redundant test code.

Please watch following video for understanding general concept of loops:

Loop Explained

In this code note, we will cover following topics related to loops:

  • for loop
  • while loop
  • do-while loop
  • Infinite loop
  • break and continue statement



while Loop

This loop is used to execute a block of code until condition result to boolean false value. If the number of code execution is not fixed, it is recommended to use the while loop.

1
2
3
4
5
6
7
8
9
int updater = 0;
while( condition ) {
    // loop body:
    // block of code that will be executed
    // only once if condition results in [true]

    // updater will make condition [false] eventually
    updater++;  
}

In the above syntax, if the condition evaluates to true, then the following execution order will take place:

  • statements inside the while loop body are executed, including the updater code.
  • then, the test condition is evaluated again.

This process goes on until the condition is evaluated to false. When the expression is evaluated to false, the while loop is terminated. Note that code block may never execute as the expression can result in false from the start.

Flow Diagram

Note that the condition can be any of the following as long as it results in boolean data, which has two possible values true and false.

  • boolean data value
  • statement with relational operators
  • statement with logical operators
  • boolean expression

Try these sample codes in the editor:

_
int number = 0;
while(number < 5) {
    System.out.println("index:" + number);
    number++;    // updater code
}
//===== OUTPUT ======//
//index:0
//index:1
//index:2
//index:3
//index:4
_
int sum = 0;
int i = 100;
while (i != 0) {
    sum += i;     // sum = sum + i;
    --i;          // updater code
}
System.out.println("Sum = " + sum);

//===== OUTPUT ======//
// Sum = 5050
Code Editor 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link



› do-while Loop

The do-while loop is similar to the while loop with one key difference. The body of the do-while loop is executed once before the condition is checked. Use this loop if the number of iterations is not fixed, and you must execute the loop body at least once before the start of loop execution.

Syntax
1
2
3
4
5
6
7
8
9
int updater = 0;
do {
   // loop body:
   // block of code that will be executed 
   // until the condition results in [false]

   // updater code:  this will make expression [false] eventually
   updater++;
} while( condition );

The body of the do-while loop is executed once before checking the condition. After that, the condition is evaluated for the next loop iteration.

If the condition evaluates to true, code inside the loop body is executed once more, and the condition is re-evaluated. This process repeats until the condition evaluates to false.

Flow Diagram

Try this sample codes in the editor:

double inputNumber;
double sum = 0.0;

Scanner input = new Scanner(System.in);   

do {
    System.out.print("Enter a number: "); 
    inputNumber = input.nextDouble();     
    sum += inputNumber;                   
} while (inputNumber != 0.0);            

System.out.println("Sum = " + sum);

//===== Sample Output ======//
// Enter a number: 90.09
// Enter a number: 89.0
// Enter a number: 0.0
// Sum = 179.09
Code Editor 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link



for Loop

The for loop is another variant of while loop, and it is by far the most used loop. Use this loop if the number of code block execution is fixed and you know exactly how many loop iteration you want to perform.

Syntax
1
2
3
4
5
for (initialization;  condition;  updater) {
    // loop body
    // code here will run one at a time 
    // until the expression results in [false]
}

To summarize, the order of for loop executions :

  1. initialization always executes only once
  2. condition
  3. loop Body
  4. updater
  5. go back to step 2, terminate once it's false, otherwise, do steps 2, 3, 4 again

Flow Diagram

Try the following sample code on code editor:

Sample Code
for (int i = 1;  i <= 3;  ++i) {
    System.out.println("Line " + i);
}

//===== OUTPUT ======//
// Line 1
// Line 2
// Line 3

//---- for loop parts ----//
// initialization:   int i = 1;
// expression    :   i <= 5;
// loop body     :   System.out.println("Line " + i);
// updater       :   ++i
Code Editor 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link



› Infinite Loop

We should always be careful while working with loops.  The loop will run forever if we mistakenly set the condition to be never false.  This situation is called an infinite loop. Let's look at how we can make an infinite loop with each loop type.

while loop example
//-- infinite loop #1, expression is has [true] value
while(true) {
    System.out.println("Hello");
}   

//-- infinite loop #2, expression is always evaluates to [true] since [updater] code is missing in loop body
int i = 100;
while(i == 100){
    System.out.println("Hey!");
    // no updater code like i++
}
do-while loop example
//-- infinite loop #1
do {
    System.out.println("Hello");
}while(true);


//-- infinite loop #2
int i = 100;
do{
    System.out.println("Hey!");
    // no updater code like i++
}while(i == 100);
for loop example
//-- infinite loop #1, when we only have [loop body]
for( ; ; ) {
   System.out.println("hello");
}

//-- infinite loop #2, when we forget the [updater] code
for(int i = 0 ;i < 10;  ) {
    System.out.println("hello");
}

//-- infinite loop #3, when we have wrong [expression] part, it is forever true
for(int i = 1; i <= 10; --i) {
    System.out.println("Hello");
}



break and continue

Depending on the circumstances, it is sometimes desirable to terminate or skip the loop iteration.  In Java, we can terminate the loop execution using the break statement and skip the current loop body iteration using the continue statement.  You should understand that these two statements are only usable with if statement inside the loop body.

break statement:

The break statement terminates the loop immediately if its encountered, and execution resumes to the next statement following outside the loop.

example flow

Sample Code
for (int i = 1; i <= 10; ++i) {

    System.out.println(i);

    if (i == 3) {
        break;
    }
}

//---OUTPUT---
1
2
3



continue statement:

The continue statement skips the current iteration of a loop and the control of the program moves to the execution of next loop iteration.

example flow

skipping range of numbers
1
2
3
4
5
6
7
8
9
for (int i = 1; i <= 10; ++i) {

    // if value of i is between 4 and 9, continue is executed
    if (i > 4 && i < 9) {
         continue;
    }

    System.out.println(i);
}
skipping even number
for (int idx = 1; idx <= 20; idx++) {

    // I want you to skip even numbers
    if (idx % 2 == 0) {
        System.out.print("*  ");
        continue;
    }

    System.out.print(idx + "   ");
}