Chapter 5: Loops in Java

Introduction to Loops

Sometimes we need to repeat a set of statements. For example:

  • Print "Hello World" 500 times
  • Print first 500 natural numbers
  • Print a pattern
  • In such cases, loops are used to execute a set of statements repeatedly.

    Types of Loops in Java

    1. while loop

    Executes statements while condition is true

    2. do-while loop

    Executes statements at least once, then checks condition

    3. for loop

    Most commonly used when number of iterations is known

    4. Enhanced for loop

    Used to iterate over arrays and collections

    While Loop

    The while loop executes a set of statements as long as the condition is true.

    Syntax:

    WhileSyntax.java
    while (condition) {
        // Statements to be executed
    }

    Example 1: Print numbers 1 to 10

    WhileExample.java
    public class WhileExample {
        public static void main(String[] args) {
            int i = 1;
            while (i <= 10) {
                System.out.println(i);
                i++; // Important: increment to avoid infinite loop
            }
        }
    }

    Example 2: Sum of first n natural numbers

    SumNatural.java
    import java.util.Scanner;
    
    public class SumNatural {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter n: ");
            int n = scanner.nextInt();
            
            int sum = 0;
            int i = 1;
            
            while (i <= n) {
                sum += i;
                i++;
            }
            
            System.out.println("Sum = " + sum);
            scanner.close();
        }
    }

    Important: Always ensure the loop variable is updated inside the loop to avoid infinite loops!

    Do-While Loop

    The do-while loop executes the statements at least once, then checks the condition.

    This is useful when you want to execute the loop body at least once regardless of the condition.

    Syntax:

    DoWhileSyntax.java
    do {
        // Statements to be executed
    } while (condition);

    Example: Menu-driven program

    MenuExample.java
    import java.util.Scanner;
    
    public class MenuExample {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int choice;
            
            do {
                System.out.println("\n--- Menu ---");
                System.out.println("1. Add");
                System.out.println("2. Subtract");
                System.out.println("3. Exit");
                System.out.print("Enter your choice: ");
                choice = scanner.nextInt();
                
                switch (choice) {
                    case 1:
                        System.out.println("Addition selected");
                        break;
                    case 2:
                        System.out.println("Subtraction selected");
                        break;
                    case 3:
                        System.out.println("Goodbye!");
                        break;
                    default:
                        System.out.println("Invalid choice!");
                }
            } while (choice != 3);
            
            scanner.close();
        }
    }

    While vs Do-While

    While Loop

  • Condition checked first
  • May not execute at all
  • Entry-controlled loop
  • Do-While Loop

  • Condition checked last
  • Executes at least once
  • Exit-controlled loop
  • For Loop

    The for loop is used when the number of iterations is known beforehand.

    It's the most commonly used loop in programming.

    Syntax:

    ForSyntax.java
    for (initialization; condition; increment/decrement) {
        // Statements to be executed
    }

    For Loop Components:

    1. Initialization

    Executed once at the beginning

    int i = 0

    2. Condition

    Checked before each iteration

    i < 10

    3. Update

    Executed after each iteration

    i++

    Example 1: Print numbers 1 to 10

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

    Example 2: Print multiplication table

    MultiplicationTable.java
    import java.util.Scanner;
    
    public class MultiplicationTable {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int num = scanner.nextInt();
            
            System.out.println("Multiplication table of " + num + ":");
            for (int i = 1; i <= 10; i++) {
                System.out.println(num + " x " + i + " = " + (num * i));
            }
            
            scanner.close();
        }
    }

    Enhanced For Loop (For-Each)

    The enhanced for loop is used to iterate over arrays and collections.

    It's also known as the "for-each" loop and provides a cleaner syntax.

    Syntax:

    EnhancedForSyntax.java
    for (dataType variable : array/collection) {
        // Statements to be executed
    }

    Example: Iterate over an array

    EnhancedForExample.java
    public class EnhancedForExample {
        public static void main(String[] args) {
            int[] numbers = {1, 2, 3, 4, 5};
            
            // Enhanced for loop
            System.out.println("Enhanced for loop:");
            for (int num : numbers) {
                System.out.println(num);
            }
        }
    }

    Note: Enhanced for loop is read-only. You cannot modify the array elements using this loop.

    Loop Control Statements

    Loop control statements change the execution flow of loops.

    1. break Statement

    Terminates the loop immediately

    BreakExample.java
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break; // Exit loop when i equals 5
        }
        System.out.println(i);
    }
    // Output: 1, 2, 3, 4

    2. continue Statement

    Skips the current iteration and continues with the next

    ContinueExample.java
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            continue; // Skip when i equals 5
        }
        System.out.println(i);
    }
    // Output: 1, 2, 3, 4, 6, 7, 8, 9, 10

    Nested Loops

    A loop inside another loop is called a nested loop.

    Nested loops are useful for working with 2D arrays, patterns, and complex iterations.

    Example 1: Print a pattern

    StarPattern.java
    public class StarPattern {
        public static void main(String[] args) {
            int rows = 5;
            
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print("* ");
                }
                System.out.println();
            }
        }
    }
    
    // Output:
    // * 
    // * * 
    // * * * 
    // * * * * 
    // * * * * *

    Example 2: Number pattern

    NumberPattern.java
    public class NumberPattern {
        public static void main(String[] args) {
            int rows = 4;
            
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(j + " ");
                }
                System.out.println();
            }
        }
    }
    
    // Output:
    // 1 
    // 1 2 
    // 1 2 3 
    // 1 2 3 4

    Practice Set

    Quick Quiz 1:

    What will be the output of this code?

    Quiz1.java
    for (int i = 0; i < 5; i++) {
        if (i == 3) {
            continue;
        }
        System.out.print(i + " ");
    }

    Answer: 0 1 2 4 (3 is skipped due to continue)

    Quick Quiz 2:

    How many times will "Hello" be printed?

    Quiz2.java
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 2; j++) {
            System.out.println("Hello");
        }
    }

    Answer: 6 times (3 × 2 = 6)

    Chapter 5 - Practice Set

    1. Pattern Printing

    Write a program to print the following pattern:

    ****
    ***
    **
    *

    2. Sum of Even Numbers

    Write a program to sum first n even numbers using a while loop.

    3. Multiplication Table

    Write a program to print multiplication table of 10 in reverse order.

    4. Factorial

    Write a program to find factorial of a given number using for loops.

    5. Prime Numbers

    Write a program to print all prime numbers between 1 and 50.

    6. Fibonacci Series

    Write a program to print first n terms of Fibonacci series.

    ← Previous: Conditionals Array →