Introduction to the Lesson

Welcome to our exploration of how to combine Java loop structures with conditional statements. By merging these elements together, your loops will be supercharged, enabling them to perform versatile actions based on different conditions.

Reviewing Java Loop Structures

Before charging forward, it's essential to revisit the foundation: loops. Within the vast cosmos of Java, we've navigated two primary types of loops: the for and while loops.

A for loop iterates a predetermined number of times, much like a reliable spaceship following a set route:

for (int i = 0; i < 5; i++) { // Iterates five times
    System.out.println(i); // Prints 0 to 4
}

The while loop, on the other hand, repeats actions until a specified condition turns false:

int i = 0;
while (i < 5) { // Condition for the loop to continue
    System.out.println(i); // Prints 0 to 4
    i++; // Increment the counter
}
Reviewing Java Conditional Statements

Let's now revisit the if-else construct, which is Java's machinery for making decisions.

int asteroidsDistance = 10;

if (asteroidsDistance > 15) { // If this condition is true
    System.out.println("Navigate through the asteroids."); // This line executes
} else {
    System.out.println("Steer clear of the asteroids."); // Else, this line executes
}

The if-else statement enables the spaceship to decide whether to navigate through the asteroids based on their distance.

Combining Loops and Conditional Statements

Next, consider how the for loop integrates with an if-else statement:

for (int i = 0; i < 6; i++) { // Our loop will iterate 6 times
    if (i % 2 == 0) { // If the number is divisible by 2 (Even)
        System.out.println(i + " is even."); // It'll print "X is even."
    } else { // If not divisible by 2 (Odd)
        System.out.println(i + " is odd."); // It'll print "X is odd."
    }
}
// Prints:
// 0 is even.
// 1 is odd.
// 2 is even.
// 3 is odd.
// 4 is even.
// 5 is odd.

In a similar fashion, an if-else statement can be applied within a while loop:

int i = 0;
while (i < 7) { // Our loop will iterate 7 times
    if (i % 3 == 0) { // If the number is divisible by 3
        System.out.println(i + " is divisible by 3."); // It'll print "X is divisible by 3."
    } else { // If not divisible by 3
        System.out.println(i + " is not divisible by 3."); // It'll print "X is not divisible by 3."
    }
    i++; // Increments the counter.
}
// Prints:
// 0 is divisible by 3.
// 1 is not divisible by 3.
// 2 is not divisible by 3.
// 3 is divisible by 3.
// 4 is not divisible by 3.
// 5 is not divisible by 3.
// 6 is divisible by 3.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal