Looping Control Statements
- Looping control statements are also called iteration statements.
- These statements are used to execute a block of statements repeatedly.
- An expression is required for looping control statements which returns boolean value.
- Block notation is mandatory when looping block has more than one statement.
- Block notation is optional when looping block has only one statement.
- When you declare any variable within loop block, that variable can be accessed only within that block. It cannot be accessed outside that block.
2.9.2.1 for Statement
Syntax
for (<initialization>; <condition>; <updation>) {
// Statements
}
Processing Flow of for Statement
Key Points
- Initialization statement will be executed only once (at the beginning).
- Condition and updation statements can be executed multiple times.
Lab186.java
class Lab186 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
System.out.println(6);
System.out.println(7);
System.out.println(8);
System.out.println(9);
System.out.println(10);
}
}
Lab187.java
class Lab187 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Lab188.java
class Lab188 {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) System.out.println(i);
}
}
}
Lab189.java
class Lab189 {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= 10; i++) System.out.println(
n + " * " + i + " = " + (n * i)
);
}
}
Lab190.java
class Lab190 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
int a = 99;
a++;
System.out.println(i + "\t" + a);
}
}
}
Lab191.java
class Lab191 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) System.out.println(i);
System.out.println(i); // Compilation Error
}
}
Lab192.java
class Lab192 {
public static void main(String[] args) {
int i = 1;
for (; i <= 10; i++) System.out.println(i);
System.out.println("After: " + i);
}
}
Lab193.java
class Lab193 {
public static void main(String[] args) {
for (;;) {
System.out.println("JavaWorld");
}
}
}
👉 This is an infinite loop
LabLab194.java
class Lab194 {
public static void main(String[] args) {
for (int i = 1,char ch = 'A';i<=10;i++) {
System.out.println(i);
}
}
}
Compilation Error
(Invalid variable declaration inside for-loop initialization)
Key Concepts
Difference between normal print & loop
- Lab186 → manual printing
- Lab187 → same using loop (efficient)
Loop Use Cases
- Print numbers →
1 to 10 - Print even numbers →
i % 2 == 0 - Multiplication table →
n * i
Variable Scope in Loop
- Variable declared inside loop → not accessible outside → (Lab191 error)
Infinite Loop
for(;;)
- No condition → always true → infinite execution
Flexible for-loop syntax
for (;condition;update)
- Initialization can be outside (Lab192)
Important Rule
- In
for(initialization)→ variables must be of same type - Cannot mix:
int i=1,char ch='A'// invalid
Lab195.java
class Lab195 {
public static void main(String[] args) {
int a;
char ch;
float f;
String str;
for (
a = 5, ch = 'A', f = 123456.78F, str = "";
a >= 0;
a--, ch++, f /= 10, str = str + ch
) {
System.out.println(a + "\t" + ch + "\t" + f + "\t" + str);
}
}
}
Lab196.java
class Lab196 {
public static void main(String[] args) {
int i = 1;
for (
System.out.println("Start"), System.out.println("Begin");
i <= 5;
i++, System.out.println("Updating"), System.out.println("Updating")
) {
System.out.println(i);
}
}
}
Lab197.java
class Lab197 {
public static void main(String[] args) {
for (int i = 0,System.out.println("Begin");
i<5;
i++,System.out.println("Updating")) {
System.out.println(i);
}
}
}
Lab198.java
class Lab198 {
public static void main(String[] args) {
boolean b1 = true;
for (; b1; ) {
System.out.println("JavaWorld");
}
System.out.println("AFTER");
}
}
Lab199.java
class Lab199 {
public static void main(String[] args) {
final boolean b1 = true;
for (; b1; ) {
System.out.println("JavaWorld");
}
System.out.println("AFTER");
}
}
Key Concepts
Multiple Variables in for-loop
for(a=5,ch='A',f=...,str="")
- You can declare/update multiple variables
- All updates run in each iteration
Multiple Statements in Initialization & Update
for(System.out.println("Start"),System.out.println("Begin"); ...)
- Allowed using comma (,)
- Execution order is left → right
Important Restriction (Lab197 )
int i=0,System.out.println("Begin")
- Invalid
- Initialization must contain only variable declarations or expressions, not mixed improperly
Infinite Loop using boolean
boolean b1=true;
for(;b1; )
- Runs forever because condition is always true
Compile-Time Infinite Loop (Important)
final boolean b1=true;
for(;b1; )
- Compiler knows condition is always true
- So next line:
System.out.println("AFTER");
Unreachable statement → Compilation Error
Difference Summary
| Case | Behavior |
|---|---|
boolean b1 = true | Runtime infinite loop |
final boolean b1 = true | Compile-time error (unreachable code) |
Execution Flow Example (Lab196)
- Initialization → prints:
- Start
- Begin
- Loop starts
- Each iteration:
- Print
i - Print "Updating" twice
- Increment
i
- Print
Lab200.java
class Lab200 {
public static void main(String[] args) {
byte b = 127;
b++; // overflow
System.out.println(b);
for (byte by = 10; by > 0; by++) {
System.out.println(by);
}
}
}
Lab201.java
class Lab201 {
public static void main(String[] args) {
int val = 2147483640;
for (; val > 200; val++) {
System.out.println(val);
}
System.out.println("After Loop :" + val);
}
}
Lab202.java
Output Pattern
A
A A
A A A
A A A A
A A A A A
Code
class Lab202 {
public static void main(String[] args) {
char ch = 'A';
for (int rows = 0; rows < 5; rows++) {
for (int cols = 0; cols <= rows; cols++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
2.9.2.2 Enhanced For Statement
- It is a new feature added in Java 5
- It is also called for-each loop
- Mainly used to access elements from array/collection sequentially
Syntax
for (<dataType>varName :array|collection) {
// Statements (BLOCK)
}
Key Concepts
✔ Byte Overflow (Lab200)
byterange → 128 to 127
byte b=127;
b++;// becomes -128
✔ Loop with byte (Important ⚠️)
for(byte by=10;by>0;by++)
- Infinite loop risk due to overflow behavior
✔ Integer Overflow (Lab201)
intmax → 2147483647- After exceeding → wraps to negative value
✔ Nested Loop Pattern (Lab202)
- Outer loop → controls rows
- Inner loop → controls columns
- Used for pattern printing
✔ Enhanced for-loop (for-each)
Example:
int arr[]= {1,2,3,4};
for (int x :arr) {
System.out.println(x);
}
✔ When to Use for-each
- When you only need to read values
- Not suitable when:
- You need index
- You want to modify elements
2.9.2.3 while Statement
Syntax
<initialization>
while (<condition>) {
// Statements (LOOP BODY)
<updation>
}
✔ Important Rule
- Condition in
whilestatement is mandatory - It must be of boolean type
Processing Flow of while Statement
Lab203.java
class Lab203 {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
}
}
Lab204.java
class Lab204 {
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
System.out.println(i);
}
}
}
Key Concepts
✔ Structure Difference from for-loop
| for-loop | while-loop |
|---|---|
| All in one line | Separated |
for(init; cond; update) | init + while(cond) + update |
✔ Execution Flow
- Initialization → runs once
- Condition → checked
- If true → loop body executes
- Update happens
- Repeat until condition becomes false
✔ Important Behavior (Lab204)
while(i++<10)
- Uses post-increment
- First compares, then increments
Output:
1
2
3
...
10
✔ Key Difference Example
| Expression | Meaning |
|---|---|
i++ < 10 | compare then increment |
++i < 10 | increment then compare |
Lab205.java
class Lab205 {
public static void main(String[] args) {
while() {
System.out.println("JavaWorld");
}
}
}
Result:
- Compile-time error
- Condition is mandatory → cannot leave
while()empty
Lab206.java
class Lab206 {
public static void main(String[] args) {
while (true) {
System.out.println("JavaWorld");
}
}
}
✔ Output:
JavaWorld
JavaWorld
JavaWorld
...
- Infinite loop
Lab207.java
class Lab207 {
public static void main(String[] args) {
while (true) {
System.out.println("JavaWorld");
}
System.out.println("AFTER");
}
}
Result:
- Compile-time error
AFTERis unreachable statement
Lab208.java
class Lab208 {
public static void main(String[] args) {
boolean b1 = true;
while (b1) {
System.out.println("JavaWorld");
}
System.out.println("AFTER");
}
}
✔ Output:
JavaWorld
JavaWorld
JavaWorld
...
- Infinite loop (since
b1is always true) AFTERnever executes
Lab209.java
class Lab209 {
public static void main(String[] args) {
int n = 5,
i = 0;
while (i++ < 10) {
System.out.println(n * i);
}
}
}
✔ Output:
5
10
15
20
25
30
35
40
45
50
Lab210.java
class Lab210 {
public static void main(String[] args) {
int n = 5,
i = 0;
while (i++ < 10) System.out.println(n * i);
}
}
✔ Output:
5
10
15
20
25
30
35
40
45
50
{}optional for single statement
Lab211.java
class Lab211 {
public static void main(String[] args) {
char ch = 'A';
int rows = 0;
while (rows < 5) {
int cols = 0;
while (cols <= rows) {
System.out.print(ch + " ");
cols++;
}
System.out.println();
rows++;
}
}
}
✔ Output:
A
A A
A A A
A A A A
A A A A A
🔑 Key Takeaways
✔ While Loop Rules
- Condition must be boolean
- Empty condition → compile error
while(true)→ infinite loop
✔ Infinite Loop + Code After
while(true) { }
System.out.println("Hello");
➡ Unreachable statement error
✔ Post Increment in Condition
while(i++<10)
- First compare → then increment
- Very common interview trap ⚠️
✔ Nested while loop
- Used for patterns (like Lab211)
- Outer loop → rows
- Inner loop → columns
2.9.2.4 do-while Statement
✔ When you are using for statement or while statement, the condition is verified before executing the block.
✔ So in the case of for and while, if the condition is false the first time, the block will not be executed.
✔ for and while statements are also called Entry Controlled Loop.
✔ If you want to execute the block at least once, then use do-while statement.
Using do-while loop
✔ In do-while, first the block of statements will be executed, and then the condition is verified.
✔ do-while statement is also called an Exit Controlled Loop.
Processing Flow of do-while statement
Flow Explanation:
- Initialization
- Execute Loop Body
- Perform Update
- Check Condition
- If true → repeat loop
- If false → STOP
Equivalent Structure
do {
// Statements (Loop Body)
}while (condition);
Key Difference (Important for Interviews)
| Loop Type | Condition Check | Executes at least once? |
|---|---|---|
| while | Before loop | Not guaranteed |
| for | Before loop | Not guaranteed |
| do-while | After loop | Always once |
Diagram (do-while)
Lab212.java
class Lab212 {
public static void main(String[] args) {
int a = 0;
do {
System.out.println("Value of a: " + a);
a--;
} while (a > 20);
}
}
✔ Output:
Value of a: 0
- Loop executes once (do-while guarantee), then condition becomes false
Lab213.java
class Lab213 {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 10);
}
}
✔ Output:
1
2
3
4
5
6
7
8
9
10
Lab214.java
class Lab214 {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i++);
} while (true);
}
}
✔ Output:
0
1
2
3
...
- Infinite loop
Lab215.java
class Lab215 {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i++);
} while (true);
System.out.println("AFTER");
}
}
Result:
- Compile-time error
"AFTER"is unreachable statement
Lab216.java
class Lab216 {
public static void main(String[] args) {
char ch = 'A';
int rows = 0;
do {
int cols = 0;
do {
System.out.print(ch + " ");
cols++;
} while (cols <= rows);
System.out.println();
rows++;
} while (rows < 5);
}
}
✔ Output:
A
A A
A A A
A A A A
A A A A A
Key Takeaways
✔ do-while Behavior
- Executes at least once (even if condition is false)
- Condition is checked after execution
✔ Infinite Loop Case
do {
// code
}while(true);
➡ Runs forever unless break is used
✔ Unreachable Code
do {
}while(true);
System.out.println("Hello");
➡ Compile-time error
✔ Nested do-while
- Useful for pattern printing
- Outer loop → rows
- Inner loop → columns