Beginner Reference Manual • Chapter 2

Making Decisions & Repeating Actions (Control Flow & Loops)

Learn how programs make smart choices using if-else decisions, pick between options using switch statements, and automate repetitive tasks using loops.

Programs become powerful when they can think for themselves! In this chapter, you will learn how to make your code take different paths based on conditions (like a traffic light) and repeat tasks automatically thousands of times without writing repetitive code.

2.1. 1. Making Decisions: if, else if, and else

Definition: An if-else statement allows a program to test a condition and choose which path of code to run based on whether that condition is true or false.

Core Working Principles:

🚦 Layman Analogy: Traffic Light Decision Rules

Think of driving up to an intersection:
• IF light is Green: Drive forward!
• ELSE IF light is Yellow: Slow down and prepare to stop.
• ELSE (light is Red): Stop completely!

graph TD
    Start[User Inputs Age] --> Check{Is Age >= 18?}
    Check -->|Yes True| Pass[Print: Access Granted]
    Check -->|No False| Block[Print: Access Denied]
                    
Architecture Specification 2.1: Decision-making flowchart using if-else logic
int age = 20;

if (age >= 18) {
    System.out.println("Access Granted: You are an adult.");
} else {
    System.out.println("Access Denied: You must be 18 or older.");
}
5-Marks Exam Scoring Points
  • if-else statements allow programs to make decisions dynamically.
  • Conditions evaluate to true or false using comparison operators like >= or ==.
  • The else block runs as a fallback when all previous conditions fail.

2.2. 2. Multi-Option Selection: The switch Statement

Definition: A switch statement is a clean, organized way to pick one option out of many based on an exact matching value.

Core Working Principles:

🛗 Layman Analogy: Elevator Floor Buttons

When you get into an elevator:
• Press Button 1 $ ightarrow$ Elevator stops at Floor 1.
• Press Button 2 $ ightarrow$ Elevator stops at Floor 2.
• Press Button 3 $ ightarrow$ Elevator stops at Floor 3.

The elevator doesn't check every floor sequentially—it jumps directly to your selected button!

int dayNumber = 3;

switch (dayNumber) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday"); // Matches! Prints Wednesday
        break;
    default:
        System.out.println("Invalid Day Number");
}
5-Marks Exam Scoring Points
  • Use switch statements when matching a single variable against multiple fixed values.
  • Always use break statements after each case to exit cleanly.
  • default acts like an else block when no options match.

2.3. 3. Automating Repetition: for and while Loops

Definition: A loop automatically repeats a block of code multiple times without needing to write duplicate code.

Core Working Principles:

🏃 Layman Analogy: Running Laps on a Track

Imagine running 5 laps around a sports field:
• Start at Lap 1.
• After completing each lap, add 1 to your counter (Lap 1 $ ightarrow$ Lap 2 $ ightarrow$ Lap 3).
• When your counter reaches 5, stop running!

// FOR LOOP: Counts from 1 to 5
for (int lap = 1; lap <= 5; lap++) {
    System.out.println("Running Lap number: " + lap);
}

// WHILE LOOP: Repeats while battery is less than 100%
int battery = 80;
while (battery < 100) {
    System.out.println("Charging... Current battery: " + battery + "%");
    battery += 10; // Increase battery by 10
}
5-Marks Exam Scoring Points
  • Loops eliminate duplicate code by repeating actions automatically.
  • The for loop manages counter initialization, condition checking, and incrementing in one line.
  • Ensure loops have an eventual exit condition to prevent infinite loops!

✍️ Chapter 2 Reference Exercises & Review Problems

Exercise 2.1: Write the logic for an Exam Grading System (Score >= 90 -> Grade A, >= 80 -> B, >= 70 -> C, Else -> Fail).
Step-by-Step Reference Code:
int score = 85;

if (score >= 90) {
    System.out.println("Grade: A");
} else if (score >= 80) {
    System.out.println("Grade: B"); // Runs! 85 is >= 80
} else if (score >= 70) {
    System.out.println("Grade: C");
} else {
    System.out.println("Grade: Fail");
}
Exercise 2.2: What is the main difference between a `for` loop and a `while` loop?
Step-by-Step Explanation for Beginners:
- Use a for loop when you know the exact number of iterations in advance (e.g., 'Do this action 10 times').
- Use a while loop when you don't know how many times it will run beforehand, and want to keep repeating until a specific condition becomes false (e.g., 'Keep downloading until the file is complete').