Break & Continue Statements and Pattern Programming in Java
Loops in Java are powerful, but sometimes you need to control their execution. That’s where break and continue come in. We’ll also cover pattern programming examples, which are commonly asked in interviews.
Break Statement
- Terminates the current loop immediately.
- Used to exit early when a condition is met.
Syntax :
break;
➤ Flowchart for Break Statement
┌─────────────┐
│ Start Loop │
└──────┬──────┘
↓
┌───────────────┐
│ Condition met? │
└──────┬────────┘
Yes ↓ No ↓
┌───────────────┐ │
│ break → Exit │ │
│ from loop │ │
└───────────────┘ │
↓
Next iterationExample: Stop loop when number equals 5
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // exit loop
}
System.out.println(i);
}
Output:
1
2
3
4
Continue Statement
- Skips current iteration and moves to the next iteration.
- Useful when you want to ignore certain conditions.
Syntax:
continue;
➤ Flowchart for Continue Statement
┌─────────────┐
│ Start Loop │
└──────┬──────┘
↓
┌───────────────┐
│ Condition met? │
└──────┬────────┘
Yes ↓ No ↓
┌────────────────────┐
│ continue → Skip │
│ current iteration │
└────────────────────┘
↓
Next iterationExample: Skip number 5
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // skip this iteration
}
System.out.println(i);
}
Output:
1
2
3
4
6
7
8
9
10
Nested Loops with Break & Continue
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break; // exits inner loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=3, j=1
i=3, j=2
i=3, j=3
⚠️ Tip: For breaking outer loops, use labeled break:
outerLoop:
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2 && j==2) break outerLoop;
}
}
Pattern Programming Examples (Practice Problems For Students)
Pattern programming is popular in Java interviews. Let’s look at common patterns.
1. Right-Angled Triangle
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
2. Inverted Triangle
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
* * * * *
* * * *
* * *
* *
*
3. Pyramid Pattern
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = n; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= (2*i-1); k++) {
System.out.print("*");
}
System.out.println();
}
Output:
*
***
*****
*******
*********
Tips for Pattern Programming
- Understand row and column relationships.
- Use nested loops carefully.
- Start with simple patterns, then try complex patterns.
- Many interview questions are variations of triangles, pyramids, and diamonds.
