Iteration Statements

  • Introduction to Loops

    • In general, statements are executed sequentially – the first statement in a method is executed first, followed by the second, the third, and so on.

    • There are times when you need to execute a block of code multiple times; often with variations in each execution.

    • Programming languages provide flow-control structures that allow more complicated execution paths.

    • Loop statements allow for executing a single statement or group of statements multiple times.

    • A loop is typically controlled by an index or counter variable.

  • Why Loops?

    • Repeated Actions:

      • Suppose we need to print a string (e.g., "Welcome to Java World!") 100 times. It would be tedious to have to write the following statement a hundred times:

        System.out.println("Welcome to Java World!");
        
        • How do you solve this problem?

  • Opening Problem

    • Suppose you want to print "Welcome to Java World!" 100 times. You could write the following code:

      System.out.println("Welcome to Java World!")
      System.out.println("Welcome to Java World!")
      System.out.println("Welcome to Java World!")
      ...
      ...
      System.out.println("Welcome to Java World!")
      System.out.println("Welcome to Java World!")
      System.out.println("Welcome to Java World!")

      This would be very tedious and time-consuming. However, there is an easier way to accomplish this task using loops.

  • Loop Statement Flowchart

    • The diagram illustrates a loop statement:

  • Types of Loops in Java

    • Java supports three loop statements:

      • for loop

        • Executes a sequence of statements multiple times over a range of values, and abbreviates the code that manages the loop variable.

      • while loop

        • Repeats a statement or group of statements while a given condition is true.

        • Evaluates the condition before executing the loop body.

      • do-while loop

        • Similar to while loop, except that the condition is evaluated after the statements are executed.

        • Guarantees that the loop executes at least once.

  • Introduction to for Loops

    • A for loop in Java iterates over the items in any sequence:

      • The statement(s) within the for loop will repeat until the entire sequence has been visited.

      • For loops are often used to iterate through all elements in a collection.

      • A for loop has three parts:

        • Initialization.

        • Continuation condition.

        • Action-after-each-iteration.

      General Syntax:

      for (initialize action; continuation-condition; after-iteration-action) {
        // Loop body
        statement(s);
      }
      
  • Nested Loops

    • The placement of one loop inside the body of another loop is called nesting.

    • When we nest two loops, the outer loop takes control of the number of complete repetitions of the inner loop.

    • Any type of loop may be nested.

    • Following is the basic Syntax for the "Nested for loop”:

    // ---outer loop---
    for (int i = 1; i <= 5; ++i) {
        // codes in the body of the outer loop
        // ---inner loop--
        for(int j = 1; j <=2; ++j) {
        }
    }
    
  • Nested Loop Example

    • Nested Loop Example

      Here is an example of a nested loop in Java:

      public class NestedLoopExample {
          public static void main(String[] args) {
              int weeks = 3;
              int days = 7;
      
              // Outer loop prints weeks
              for (int i = 1; i <= weeks; ++i) {
                  System.out.println("Week: " + i);
      
                  // Inner loop prints days
                  for (int j = 1; j <= days; ++j) {
                      System.out.println("Day: " + j);
                  }
              }
          }
      }
      

      The expected output is:

      Week: 1
      Day: 1
      Day: 2
      Day: 3
      Day: 4
      Day: 5
      Day: 6
      Day: 7
      Week: 2
      Day: 1
      Day: 2
      Day: 3
      Day: 4
      Day: 5
      Day: 6
      Day: 7
      Week: 3
      Day: 1
      Day: 2
      Day: 3
      Day: 4
      Day: 5
      Day: 6
      Day: 7
      
  • Enhanced for Loops

    • The for statement has another form designed to iterate through arrays and collections.

    • The syntax of the Java enhanced loop is that it can be applied to arrays, various collection classes, and any class implementing the Iterable interface.

    Example usage:

    for(dataType item : array) {
        // statement ....
    }
    

    In the example above:

    • array - an array or a collection.

    • item - a variable array/collection assigned.

    • dataType - the data type of the array/collection.

  • Enhanced for Loops (continued)

    Syntax:

    for (T element : Collection obj/array) {
        statement(s);
    }
    

    Example:

    public class enhanceforloop {
        // Java program to illustrate enhanced for Loop
        public static void main (String args []) {
            String movies [] = {"Braveheart", "Troy", "Life is beautiful"};
            //enhanced for Loop
            for (String value: movies) {
                System.out.println(value);
            }
            // for Loop for same function
            // for (int i = 0; i < movies.length; i++) {
            //    System.out.println(movies[i]);
            // }
        }
    }
    
  • Introduction to while Loops

    • As the name suggests, while loop will continually process a statement or given code block while its evaluation condition is true.

    • Syntax:

    while (condition){
       //statement(s)
    }
  • while Loop Flowchart

  • while Loop Flowchart Example

Trace for Loop

It is also valid to declare i before the loop, giving i greater scope:

Declare and initialize i; i is now 0.
Declare i variable
Initialize 0 value in variable i

Trace for Loop - Iteration #1 Test for Continuation #1

for (int i=0; i<2; i++){
    System.out.println("Welcome to Java!");
}
System.out.println("Goodbye!");
// i is 0, so i <2 is true.
// Execute the Loop Body #1
// Print “Welcome to Java!”
// Execute the post-iteration action: Increment i.
// i is now 1.

Trace for Loop: Iteration #2 Test for Continuation #2

for (int i=0; i<2; i++){
    System.out.println("Welcome to Java!");
}
System.out.println("Goodbye!");
// i is 1; so i <2 is still true.
// Print “Welcome to Java!”
// Execute the post-iteration action: Increment i.
// i is now 2.

A Misplaced Semicolon

Adding a semicolon at the end of the for clause before the loop body is a common mistake — a logic error:

for (int i=0; i<10; i++); {
    System.out.println("i is " + i);
}

Nested Loops

  • The placement of one loop inside the body of another loop is called nesting.

  • When we nest two loops, the outer loop takes control of the number of complete repetitions of the inner loop.

  • Any type of loop may be nested.

  • Following is the basic Syntax for the "Nested for loop”:

// ---outer loop---
for (int i = 1; i <= 5; ++i) {
    // codes in the body of the outer loop
    // ---inner loop--
    for(int j = 1; j <=2; ++j) {
    }
}
// code in the body of both outer and inner loops

Nested Loop Example

public class NestedloopExample{
    int weeks = 3;
    int days = 7;
    // outer loop prints weeks
    for (int i = 1; i <= weeks; ++i) {
        System.out.println("Week: " + i);
        // inner loop prints days
        for (int j = 1; j <= days; ++j) {
            System.out.println("Day: " + j);
        }
    }
}

Topic 1b: Enhanced for Loops

The for statement has another form designed to iterate through arrays and collections. The syntax of the Java enhanced loop is that it can be applied to arrays, various collection classes, and any class implementing the Iterable interface.

for(dataType item : array) {
}
statement ....

In the example above:

  • array - an array or a collection.

  • item - a variable array/collection assigned.

  • dataType - the data type of the array/collection.

Hands-On Lab - for loop

Complete this lab GLAB- 303.5.1- For Loop. You can find this lab on Canvas under the Assignment section. Use your office hours to complete this Lab. If you have technical questions while performing the Lab activity, ask your instructors for assistance.

Topic 1c: Introduction to while Loops

As the name suggests, while loop will continually process a statement or given code block while its evaluation condition is true.

while (condition){
    //statement(s)
    // statement1...n
    condition = false;
}

while Loop Flowchart

while (condition){
    //statement(s);
}

The condition must evaluate to true for the body of the while loop to execute (just like the if statement and for loop).

while Loop Flowchart Example

int count = 0;
while (count < 100){
    System.out.println("Welcome to Java!");
    count++;
}
int count = 0;
while (count < 2) {
    System.out.println("Welcome to Java!");
    count++;
}
System.out.println("Goodbye!");

Trace while Loop

Initialize count. (count < 2) is true.

int count = 0;
while (count < 2) {
    System.out.println("Welcome to Java!");
    count++;
}
System.out.println("Goodbye!");
// Print “Welcome to Java!”
// Increment count by 1; count is now 1.
int count = 0;
while (count < 2) {
    System.out.println("Welcome to Java!");
    count++;
}
System.out.println("Goodbye!");
// (count < 2) is still true since count is 1.
// Print “Welcome to Java!”
// Increase count by 1; count is 2 now.
int count = 0;
while (count < 2) {
    System.out.println("Welcome to Java!");
    count++;
}
System.out.println("Goodbye!");
// (count < 2) is false since count is 2 now.

Omitting the Loop-Continuation-Condition

If the loop-continuation-condition in a for loop is omitted, it is implicitly true. The statement (a) is valid Java. It is an infinite loop. The statement (b) is preferred just to avoid confusion.

Ending a Loop With a Sentinel Value

Often, the number of times a loop is executed is not known ahead of time. You may use a special input value to signify the end of the loop. Such a value is called a sentinel value.

Example: While loop

Make a new class and call it whileloop example. Inside, write the code shown below:

public class Whileloopexample {
    public static void main(String[] args) {
        int i = 0;
        while (i < 3) {
        }
    }
}
System.out.println("Value of i = " + i);
i++;

Output:

Value of i = 0
Value of i = 1
Value of i = 2

Hands-On Lab - While loop

Complete GLAB- 303.5.2 - While Loop. You can find this lab on Canvas under the Assignment section. Use your office hours to complete this Lab. If you have technical questions while performing the lab activity, ask your instructors for assistance.

Topic 1d: Introduction to do-while Loops

The do-while and while loop are similar, and work in a similar way, except that in a do-while loop, an expression is evaluated at the bottom as compared to the while loop. To put it in another way, the do-while loop guarantees that the loop body will execute at least once.

do {
    //Loop Body
    statement(s);
} while (loop-continuation-condition);

do-while Loop Examples

  • Finite do-while loop:

int i = 1;
do {
    System.out.println(i);
    i++;
} while(i<=10);
  • Looping while true:

do {
    System.out.println(“Infinite loop”);
} while(true);

Topic 1e: Use Which Loop?

  • Use the loop that is most intuitive and most comfortable for you.

  • In general, a for loop may be used if the number of repetitions is known. For example, you may need to print a message 100 times, or it can be supplied by the user.

  • A while loop may be used if the number of repetitions is not known. For example, it may read numbers until the input is 0 or it may read data from a database.

  • A do-while loop is a good choice when you are asking a question that will answer whether or not the loop is repeated.

Topic 2: Loop Control Statements

In this section, we will discuss the break and continue keywords.

Loop control statements

  • Loop control statements — sometimes referred to as jump statements — change loop execution from its normal sequence. Java supports the following loop control statements:

  • break – terminates the loop statement and transfers execution to the statement immediately following the loop.

  • continue – causes the loop to skip the remainder of its body and immediately jump to the top of the loop.

  • In while loops and for loops, the loop-continuation-condition will be evaluated.

Example: Using break keyword in a Loop

This program adds the integers from 1 to 20, in this order, to sum until the sum is greater than or equal to 100.

Output:

The number is 14.
The sum is 105.

Without the if statement, the program calculates the sum of the numbers from 1 to 20. Output:

The number is 20.
The sum is 210.
public class BreakExample {
    public static void main(String[] args) {
        int sum = 0;
        int number = 0;
        while (number < 20) {
            number++;
            sum += number;
            if (sum >= 100) {
                break;
            }
        }
        System.out.println("The number is " + number);
        System.out.println("The sum is " + sum);
    }
}

Last updated