DEV Community

Cover image for Control Flow: Mastering Conditional Statements and Loops
Bellamer
Bellamer

Posted on

Control Flow: Mastering Conditional Statements and Loops

This guide covers if-else, for loops, while loops, and more.

In programming, controlling the flow of execution is essential to making decisions and repeating actions in your code. Java provides robust tools for managing control flow, including conditional statements and loops. In this post, we'll dive into these fundamental concepts, exploring how they work and how you can use them to create dynamic and responsive programs.

1. Conditional Statements

1.1 The If-Else Statement

The if-else statement allows you to execute a block of code based on whether a condition is true or false. It’s like setting up a checkpoint in your program where certain code runs only if specific criteria are met.

Syntax:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}
Enter fullscreen mode Exit fullscreen mode

Example:

int marks = 75;

if (marks >= 60) {
    System.out.println("Passed with distinction!");
} else if (marks >= 40) {
    System.out.println("Passed!");
} else {
    System.out.println("Failed.");
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • If marks are 60 or higher, "Passed with distinction!" is printed.
  • If marks are between 40 and 59, "Passed!" is printed.
  • If marks are below 40, "Failed." is printed.

Challenge 1:

Write a Java program that checks if a number is positive, negative, or zero using if-else statements. Print an appropriate message for each case.

1.2 The Switch Statement

The switch statement is another way to execute code based on the value of a variable. It’s particularly useful when you need to compare a single variable against multiple possible values.

Syntax:

switch (variable) {
    case value1:
        // Code to execute if variable == value1
        break;
    case value2:
        // Code to execute if variable == value2
        break;
    // more cases...
    default:
        // Code to execute if none of the cases match
}
Enter fullscreen mode Exit fullscreen mode

Example:

int dayOfWeek = 3;
String day;

switch (dayOfWeek) {
    case 1:
        day = "Sunday";
        break;
    case 2:
        day = "Monday";
        break;
    case 3:
        day = "Tuesday";
        break;
    // more cases...
    default:
        day = "Invalid day";
        break;
}

System.out.println("Today is: " + day);
Enter fullscreen mode Exit fullscreen mode

2. Loops

Loops are powerful tools in programming that allow you to repeat a block of code multiple times. Java supports several types of loops, each suited to different scenarios.

2.1 The For Loop

The for loop is typically used when you know in advance how many times you need to iterate. It consists of three parts: initialization, condition, and iteration.

Syntax:

for (initialization; condition; iteration) {
    // Code to execute in each loop iteration
}
Enter fullscreen mode Exit fullscreen mode

Example:

for (int i = 1; i <= 5; i++) {
    System.out.println("Iteration: " + i);
}
Enter fullscreen mode Exit fullscreen mode

In this loop:

  • int i = 1; initializes the loop counter i.
  • i <= 5; sets the condition for the loop to run (as long as i is 5 or less).
  • i++ increments i by 1 after each iteration.

Challenge 2:

Create a for loop that prints the first 10 even numbers.

2.2 The While Loop

The while loop continues to execute as long as a specified condition is true. It’s often used when the number of iterations isn’t known beforehand.

Syntax:

while (condition) {
    // Code to execute while the condition is true
}
Enter fullscreen mode Exit fullscreen mode

Example:

int count = 0;

while (count < 3) {
    System.out.println("Count: " + count);
    count++;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the loop prints the value of count and increments it until count is no longer less than 3.

2.3 The Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body will execute at least once, even if the condition is false from the start.

Syntax:

do {
    // Code to execute at least once
} while (condition);
Enter fullscreen mode Exit fullscreen mode

Example:

int count = 0;

do {
    System.out.println("Count: " + count);
    count++;
} while (count < 3);
Enter fullscreen mode Exit fullscreen mode

In this case, the loop prints the value of count and increments it, just like the while loop, but it ensures the code runs at least once even if count starts at 3 or higher.

2.4 Break and Continue Statements

  • break: Exits the loop immediately, skipping any remaining iterations.
  • continue: Skips the current iteration and jumps to the next one.

Example Using Break:

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break; // Exit the loop when i is 5
    }
    System.out.println("Value of i: " + i);
}
Enter fullscreen mode Exit fullscreen mode

Example Using Continue:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue; // Skip the iteration when i is 3
    }
    System.out.println("Value of i: " + i);
}
Enter fullscreen mode Exit fullscreen mode

Challenge 3:

Write a loop that prints numbers from 1 to 10 but skips the number 5.

Summary

In this section, we've covered the essentials of controlling the flow of your Java programs using conditional statements and loops. We explored if-else, switch, for, while, and do-while loops, along with the break and continue statements.

By mastering these control flow tools, you can create more dynamic and efficient Java programs. Try out the challenges to reinforce what you've learned!

In the next post, we'll explore arrays and collections in Java, which are key to managing groups of data efficiently. Stay tuned!

Top comments (0)