Skip to content

Lesson 3: Control Flow Statements


Lesson 3: Control Flow Statements

Overview:

In Lesson 3, we delve into control flow statements, which allow us to dictate the flow of execution in a Java program. Conditional statements, such as if, else, and switch, enable us to make decisions based on conditions. Looping constructs, including for, while, and do-while, allow us to repeat actions until certain conditions are met.

Key Concepts:

  1. Conditional Statements:
    • if Statement:
      • Executes a block of code if a specified condition is true.
int age = 20;
if (age >= 18) {
    System.out.println("You are an adult.");
}

else Statement:

  • Executes a block of code if the if condition is false.
int temperature = 25;
if (temperature > 30) {
    System.out.println("It's hot outside.");
} else {
    System.out.println("The weather is pleasant.");
}

switch Statement:

  • Evaluates a variable against multiple possible values and executes the corresponding block of code.
char grade = 'B';
switch (grade) {
    case 'A':
        System.out.println("Excellent!");
        break;
    case 'B':
        System.out.println("Good job!");
        break;
    default:
        System.out.println("Keep working hard.");
}

2. Looping Constructs:

  • for Loop:
    • Repeats a block of code a specified number of times.
for (int i = 1; i <= 5; i++) {
    System.out.println("Iteration " + i);
}

while Loop:

  • Repeats a block of code while a specified condition is true.
int count = 0;
while (count < 3) {
    System.out.println("Count: " + count);
    count++;
}

do-while Loop:

  • Similar to the while loop, but the block of code is executed at least once before the condition is checked.
int num = 5;
do {
    System.out.println("Number: " + num);
    num--;
} while (num > 0);

Example:

Let’s combine conditional statements and looping constructs in a program that checks if a number is even or odd and then prints a countdown:

public class ControlFlowExample {

    public static void main(String[] args) {

        // Conditional Statement (if-else)
        int number = 15;
        if (number % 2 == 0) {
            System.out.println(number + " is even.");
        } else {
            System.out.println(number + " is odd.");
        }

        // Looping Construct (while)
        int countdown = 5;
        while (countdown > 0) {
            System.out.println("Countdown: " + countdown);
            countdown--;
        }

        // Looping Construct (for)
        for (int i = 1; i <= 3; i++) {
            System.out.println("Iteration " + i);
        }

        // Looping Construct (do-while)
        int start = 10;
        do {
            System.out.println("Start value: " + start);
            start--;
        } while (start > 5);
    }
}

This example demonstrates the use of conditional statements and looping constructs to create a program that analyzes numbers and performs countdowns.