← Back to Home

Module 1: Loops

Module Overview

Learn about the different types of loops in Java, when to use each type, and how to write efficient loop structures.

Learning Objectives

Loop Concepts Explained

While Loops

A while loop executes a block of code as long as its condition remains true.


// Example: Counting from 1 to 5 using a while loop
int count = 1;
while (count <= 5) {
    System.out.println("Count is: " + count);
    count++;
}
                

For Loops

A for loop provides a compact way to iterate over a range of values with initialization, condition, and iteration expressions.


// Example: Counting from 1 to 5 using a for loop
for (int i = 1; i <= 5; i++) {
    System.out.println("Count is: " + i);
}
                

Nested Loops

Nested loops place one loop inside another, often used for working with multi-dimensional data.


// Example: Printing a simple pattern using nested loops
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}
// Output:
// * 
// * * 
// * * *
                

Break Statement

The break statement immediately terminates the loop it's in.


// Example: Using break to exit a loop early
for (int i = 1; i <= 10; i++) {
    if (i == 6) {
        System.out.println("Breaking the loop at i = " + i);
        break;
    }
    System.out.println("Value of i: " + i);
}
                

Continue Statement

The continue statement skips the current iteration and proceeds to the next one.


// Example: Using continue to skip even numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue; // Skip even numbers
    }
    System.out.println("Odd number: " + i);
}
                

Key Topics

Loop Types and Controls

  • For loops and their variations
  • While loops and do-while loops
  • Loop control statements (break, continue)
  • Nested loops and their applications

Resources

Practice Exercises

  • Write a program that prints numbers 1-10 using different loop types
  • Create nested loops to print patterns
  • Implement a loop that finds the sum of numbers in a range
  • Debug a program with infinite loop issues

Next Steps

After completing this module:

  1. Complete the practice exercises above
  2. Review the additional resources for deeper understanding
  3. Attend the code-along session for hands-on practice
  4. Move on to Module 2 to learn about Arrays