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:
- Condition Checks: Evaluates statements using comparisons like
>(greater than),<(less than),==(equal to), or!=(not equal to). - Branching Paths:
- •
if: Runs code ONLY if the condition is TRUE. - •
else if: Checks an alternative condition if the previous check failed. - •
else: The catch-all fallback code that runs if none of the above conditions were true.
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]
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:
- Clean Alternative: Instead of writing 10 messy
else iflines,switchjumps directly to the matching case. - Key Parts:
- •
case: A specific matching option value. - •
break: Exits the switch block once a match is found (prevents falling through to other cases). - •
default: The default option if no matching case is found.
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:
- Why Loops Matter: If you need to print "Hello" 1,000 times, you don't write 1,000 print lines! You write 1 line inside a loop.
- Common Loop Types:
- •
forloop: Best when you know exactly how many times to repeat (e.g., repeat 5 times). - •
whileloop: Best when repeating until a condition changes (e.g., repeat while battery is under 100%).
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
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");
}
- 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').