The for Statement

🙋 Need help? Ask an expert now!

Let's dive into the function of loops as time-savers that will immediately take your coding to the next level. The for statement is a loop control statement that allows you to run one or many statements several times in succession. For example, let's say we wanted to print out numbers 1-50. Instead of writing fifty System.out.println(); statements, we use a loop. Start exploring loops by looking through the code below.

ForLoopExample.java
package exlcode;

public class ForLoopExample {

  public static int exampleVariableOne = 10;
  public static void main(String[] args) {
    System.out.println("Counting forward from 0-10:");
    // increments countOne by 1 and runs until the boolean expression is false
    for (int countOne = 0; countOne <= exampleVariableOne; countOne++) {
      System.out.print(countOne + " ");
    }
    System.out.println("\nCounting backward from 0-10:");
    // decrements countTwo by 1 and runs until the boolean expression is false
    for (int countTwo = exampleVariableOne; countTwo >= 0; countTwo--) {
      System.out.print(countTwo + " ");
    }
  }
}

Let's learn and remember the loop syntax. The statements inside the parenthesis of a for loop can be split into three sections:

  1. Initializing - initializes a new variable and assigns it a value
  2. Control - the condition that is tested every time the loop executes. If the condition is "true", the loop continues to run. If the condition result is "false", the loop terminates.
  3. Step - where you change the value of the initialized value by whatever is necessary. You may use assignment statements such as "+=" and "-=" or use increment/decrement. Feel free to go back and review those sections at any point.

Application Question

Consider the following code segment:

String varOne = "abcdef";
            for (int count = 0; count &amp;#60; varOne.length()-1; count++){
              System.out.print(varOne.substring(count, count+2));
            }
            

What is printed as a result of executing this code segment?