In loops, sometimes you want to stop everything or skip just one step. That’s where break
and continue
come in.
Let’s break it down π
π break
-
Completely exits the loop.
-
Often used when a certain condition is met and you don’t want to keep looping.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Loop ends here
}
System.out.print(i + " ");
}
// Output: 1 2 3 4
⏭️ continue
-
Skips just the current step, but keeps looping.
-
Useful when you want to skip a specific case.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip 3, but keep looping
}
System.out.print(i + " ");
}
// Output: 1 2 4 5
Keyword | What it does |
---|---|
break | Stops the entire loop |
continue | Skips current step, goes to next |
No comments:
Post a Comment