Java: Repeat Actions with For and While Loops

Java Loops Tutorial

Java Loops: Repeat Actions with For and While Loops

This tutorial will walk you through the basics of loops in Java, focusing on the for and while loops. Loops allow you to repeat a block of code multiple times. We’ll build three examples, starting with a simple counter and progressing to a more interactive scenario.

Example 1: Simple For Loop – Counting to 10

This example demonstrates the fundamental structure of a for loop. We’ll use it to print numbers from 1 to 10.

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

Let’s break down this code:

  • public class ForLoopExample: This declares a class named `ForLoopExample`. In Java, all code resides within classes.
  • public static void main(String[] args): This is the main method, the entry point of the program. When you run the program, the code inside this method will be executed.
  • for (int i = 1; i <= 10; i++): This is the for loop statement. It has three parts:
    • Initialization: int i = 1 – This initializes a counter variable i to 1. This happens only once at the beginning of the loop.
    • Condition: i <= 10 – This is the condition that is checked before each iteration. As long as i is less than or equal to 10, the loop will continue.
    • Increment: i++ – This is executed after each iteration of the loop. i++ increments the value of i by 1.
  • System.out.println("Iteration: " + i);: This line prints the current value of i to the console. The string “Iteration: ” is concatenated with the value of i.

How it works:

  1. Initially, i is set to 1.
  2. The condition i <= 10 (1 <= 10) is evaluated. It is true.
  3. The code inside the loop (System.out.println("Iteration: " + i);) is executed, printing “Iteration: 1”.
  4. i is incremented to 2.
  5. The condition i <= 10 (2 <= 10) is evaluated. It is true.
  6. The code inside the loop is executed again, printing “Iteration: 2”.
  7. This process continues until i becomes 11.
  8. When i is 11, the condition i <= 10 (11 <= 10) is evaluated. It is false.
  9. The loop terminates.

Potential Mistake: A common mistake is to omit the increment step (i++) or to use an incorrect increment value. This can lead to an infinite loop, where the loop never terminates.

Correction: Always ensure that the increment step is present and that the increment value is appropriate for your needs. In this case, incrementing by 1 is correct.


public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

Output:


Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
Iteration: 7
Iteration: 8
Iteration: 9
Iteration: 10

Example 2: While Loop – User Input

This example demonstrates a while loop, which continues as long as a specified condition is true. It takes user input until the user enters a specific value (e.g., “quit”).

public class WhileLoopExample {
    public static void main(String[] args) {
        String input = "";
        while (!input.equalsIgnoreCase("quit")) {
            System.out.println("Enter a command (or 'quit' to exit):");
            input = System.console().readLine();
            System.out.println("You entered: " + input);
        }
        System.out.println("Exiting the program.");
    }
}

Explanation:

  • String input = "";: Initializes a string variable input to an empty string.
  • while (!input.equalsIgnoreCase("quit")): This is the while loop statement. It continues as long as the condition !input.equalsIgnoreCase("quit") is true. input.equalsIgnoreCase("quit") compares the value of input to “quit” (case-insensitive). The ! negates the result.
  • System.out.println("Enter a command (or 'quit' to exit):");: Prompts the user to enter a command.
  • input = System.console().readLine();: Reads the user’s input from the console and stores it in the input variable. System.console() gets the console object, and readLine() reads a line of text from the console.
  • System.out.println("You entered: " + input);: Prints the user’s input to the console.

How it works:

  1. The loop starts with input being an empty string (“”).
  2. The condition !input.equalsIgnoreCase("quit") is evaluated. Since the string is empty, it’s not equal to “quit”, so the condition is true.
  3. The loop body is executed, prompting the user for input and printing the input.
  4. The user enters a command (e.g., “hello”).
  5. The loop continues, and the user enters another command (e.g., “quit”).
  6. The condition !input.equalsIgnoreCase("quit") is evaluated. Since input is now “quit”, the condition is false.
  7. The loop terminates.

public class WhileLoopExample {
    public static void main(String[] args) {
        String input = "";
        while (!input.equalsIgnoreCase("quit")) {
            System.out.println("Enter a command (or 'quit' to exit):");
            input = System.console().readLine();
            System.out.println("You entered: " + input);
        }
        System.out.println("Exiting the program.");
    }
}

Output (example):


Enter a command (or 'quit' to exit):
You entered: hello
Enter a command (or 'quit' to exit):
You entered: quit
Exiting the program.

Example 3: Nested Loops – Printing a Square

This example demonstrates nested for loops to print a square of asterisks. This is a more complex demonstration of how loops can be combined.

public class NestedLoopsExample {
    public static void main(String[] args) {
        int size = 5; // Size of the square
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print("");
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

Explanation:

  • int size = 5;: Defines the size of the square (number of rows and columns).
  • for (int i = 0; i < size; i++): The outer loop iterates through the rows of the square.
  • for (int j = 0; j < size; j++): The inner loop iterates through the columns of the square for each row.
  • System.out.print("");: Prints an asterisk without moving to the next line.
  • System.out.println();: Prints a newline character after each row is complete, moving the cursor to the beginning of the next line.

How it works:

  1. The outer loop iterates from i = 0 to i = 4.
  2. For each value of i, the inner loop iterates from j = 0 to j = 4.
  3. Inside the inner loop, an asterisk is printed for each column. So, when i = 0, you get “. When i = 1, you get ` ` and so on.
  4. After the inner loop completes for a given i, System.out.println(); moves the cursor to the next line.

public class NestedLoopsExample {
    public static void main(String[] args) {
        int size = 5; // Size of the square
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print("");
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

Output:



 
  
   
   

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.