π Why Control Flow Matters
Control flow allows your program to make decisions and repeat actions based on conditions. Itβs the difference between a static app and one that responds to inputs and logic.
π§ Conditional Statements
β
if
Statement
int age = 18;
if (age >= 18) {
System.out.println("You're eligible to vote.");
}
β
if...else
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
β
if...else if...else
int score = 75;
if (score >= 90) {
System.out.println("A Grade");
} else if (score >= 75) {
System.out.println("B Grade");
} else {
System.out.println("C Grade");
}
β
switch
Statement
Use when you have many conditions based on a single variable.
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Another day");
}
π Loops β Repeating Tasks
π for
Loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
π while
Loop
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
π do...while
Loop
Runs at least once before checking the condition.
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
π break
and continue
πΉ break
: Exits the loop
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.println(i);
}
πΉ continue
: Skips the current iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
π― Practice Example
public class LoopPractice {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
if (i % 2 == 0) continue;
System.out.println("Odd number: " + i);
}
}
}
β What You Learned
if
,else
,else if
, andswitch
for decision-makingfor
,while
, anddo...while
for loops- Using
break
andcontinue
effectively