Loops in Java
Learn how to repeat code efficiently in Java using while, do-while, for, enhanced for loops, nested loops, break, continue, and real-world iteration patterns.
Introduction
In the previous lesson, you learned how conditional statements allow Java programs to make decisions. However, many programming problems require the same operation to be performed repeatedly.
Imagine printing numbers from 1 to 100, processing thousands of customer records, repeatedly asking for valid input, or checking every item in a collection. Writing the same statements again and again would be inefficient and difficult to maintain.
Loops solve this problem by allowing a block of code to execute repeatedly while a condition remains true or for a specified number of iterations.
for (int number = 1; number <= 5; number++) {
System.out.println(number);
}1
2
3
4
5- What loops are.
- Why repetition is needed in programming.
- How loops control repeated execution.
- The main components of a loop.
- The difference between entry-controlled and exit-controlled loops.
- How the while loop works.
- How the do-while loop works.
- How the for loop works.
- How enhanced for loops work.
- How nested loops work.
- How break terminates a loop.
- How continue skips an iteration.
- How labeled break and continue work.
- How loop variables and scope work.
- What off-by-one errors are.
- How infinite loops occur.
- How counter-controlled loops work.
- How condition-controlled loops work.
- How sentinel-controlled loops work.
- How accumulator patterns work.
- How to calculate factorials.
- How to reverse numbers.
- How to calculate digit sums.
- How to check palindrome numbers.
- How to check prime numbers.
- How to generate Fibonacci numbers.
- How to build menu-driven programs.
- Common loop errors.
- Best practices for writing readable loops.
What are Loops?
A loop is a programming structure that repeatedly executes a block of code until a condition becomes false or another termination condition is reached.
START
│
▼
CHECK CONDITION
│
├── true ─────► EXECUTE CODE
│ │
│ ▼
│ UPDATE
│ │
│ └──────┐
│ │
└── false ─────► EXIT LOOP ◄┘
│
▼
CONTINUEWhy Loops are Needed
Repetition
Execute the same operation multiple times without duplicating code.
Data Processing
Process arrays, collections, records, files, and other groups of data.
Input Validation
Keep asking the user until valid input is provided.
Games
Continuously update game state until the player exits or the game ends.
Calculations
Calculate totals, averages, factorials, sequences, and repeated mathematical operations.
Automation
Repeat tasks efficiently without writing duplicate statements.
Real-World Analogy
Imagine climbing a staircase with ten steps. You repeat the same action until you reach the final step.
CURRENT STEP = 1
│
▼
HAVE WE REACHED STEP 10?
/ \
NO YES
│ │
▼ ▼
CLIMB ONE STOP
STEP
│
▼
INCREASE CURRENT STEP
│
└──────────────► CHECK AGAINHow Loops Work
1. INITIALIZE
│
▼
2. CHECK CONDITION
│
├── false ──► EXIT
│
└── true
│
▼
3. EXECUTE LOOP BODY
│
▼
4. UPDATE LOOP STATE
│
└────────────► RETURN TO CONDITIONLoop Components
// 1. Initialization
int number = 1;
// 2. Condition
while (number <= 5) {
// 3. Loop body
System.out.println(number);
// 4. Update
number++;
}INITIALIZATION
Creates starting state
CONDITION
Decides whether loop continues
BODY
Contains repeated statements
UPDATE
Changes loop stateTypes of Loops
JAVA LOOPS
├── while
│
├── do-while
│
├── for
│
├── Enhanced for
│
└── Nested LoopsEntry-Controlled Loops
An entry-controlled loop checks its condition before executing the loop body.
CHECK CONDITION FIRST
│
▼
true?
/ \
YES NO
│ │
▼ ▼
EXECUTE EXIT
BODY- while is entry-controlled.
- for is entry-controlled.
- The loop body may execute zero times.
- If the initial condition is false, the body is skipped.
Exit-Controlled Loops
An exit-controlled loop executes its body before checking the condition.
EXECUTE BODY FIRST
│
▼
CHECK CONDITION
/ \
true false
│ │
▼ ▼
REPEAT EXIT- do-while is exit-controlled.
- Its body executes before the condition is checked.
- The body always executes at least once.
while Loop
The while loop repeatedly executes a block of code while its condition remains true.
while Loop Syntax
while (condition) {
// Statements
}How while Works
START
│
▼
CONDITION?
├── false ─────► EXIT
│
└── true
│
▼
EXECUTE BODY
│
▼
UPDATE
│
└────────► CONDITIONBasic while Example
int number = 1;
while (number <= 5) {
System.out.println(number);
number++;
}1
2
3
4
5Counting Forward
int count = 1;
while (count <= 10) {
System.out.println(count);
count++;
}Counting Backward
int count = 10;
while (count >= 1) {
System.out.println(count);
count--;
}
System.out.println("Go!");while with User Input
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int number = 0;
while (number != 10) {
System.out.print(
"Enter 10: "
);
number =
scanner.nextInt();
}
System.out.println(
"Correct!"
);
}
}Sentinel-Controlled Loop
A sentinel value is a special value used to indicate that input or processing should stop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int number = 0;
while (number != -1) {
System.out.print(
"Enter a number (-1 to stop): "
);
number =
scanner.nextInt();
}
System.out.println(
"Program stopped."
);
}
}Sum using while
int number = 1;
int sum = 0;
while (number <= 100) {
sum += number;
number++;
}
System.out.println(
"Sum: " + sum
);Infinite while Loop
while (true) {
System.out.println(
"Running..."
);
}- An infinite loop never reaches a false condition.
- It may be intentional in servers, games, and event loops.
- Unintentional infinite loops usually happen because the loop state is never updated.
- Always verify how a loop will terminate.
do-while Loop
The do-while loop executes its body first and checks the condition afterward. Therefore, its body always executes at least once.
do-while Syntax
do {
// Statements
} while (condition);How do-while Works
START
│
▼
EXECUTE BODY
│
▼
UPDATE
│
▼
CONDITION?
├── true ─────► EXECUTE BODY AGAIN
│
└── false ────► EXITBasic do-while Example
int number = 1;
do {
System.out.println(number);
number++;
} while (number <= 5);while vs do-while
while
Condition checked first
May execute zero times
Entry-controlled
do-while
Body executed first
Executes at least once
Exit-controlledint number = 10;
while (number < 5) {
System.out.println(
"while executed"
);
}
do {
System.out.println(
"do-while executed"
);
} while (number < 5);do-while executedMenu using do-while
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int choice;
do {
System.out.println(
"1. Add"
);
System.out.println(
"2. Edit"
);
System.out.println(
"3. Delete"
);
System.out.println(
"4. Exit"
);
System.out.print(
"Enter choice: "
);
choice =
scanner.nextInt();
switch (choice) {
case 1 ->
System.out.println(
"Add selected"
);
case 2 ->
System.out.println(
"Edit selected"
);
case 3 ->
System.out.println(
"Delete selected"
);
case 4 ->
System.out.println(
"Goodbye!"
);
default ->
System.out.println(
"Invalid choice"
);
}
} while (choice != 4);
}
}Input Validation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int age;
do {
System.out.print(
"Enter age (0-120): "
);
age =
scanner.nextInt();
} while (
age < 0 || age > 120
);
System.out.println(
"Valid age: " + age
);
}
}for Loop
The for loop is commonly used when the number of iterations is known or controlled by a counter.
for Loop Syntax
for (
initialization;
condition;
update
) {
// Statements
}How for Works
INITIALIZATION
│
▼
CONDITION?
├── false ─────► EXIT
│
└── true
│
▼
EXECUTE BODY
│
▼
UPDATE
│
└────────► CONDITIONfor Loop Execution Order
1. INITIALIZATION
Runs once
2. CONDITION
Checked before every iteration
3. BODY
Runs when condition is true
4. UPDATE
Runs after the body
5. RETURN TO CONDITIONBasic for Example
for (
int number = 1;
number <= 5;
number++
) {
System.out.println(number);
}Counting Backward with for
for (
int number = 10;
number >= 1;
number--
) {
System.out.println(number);
}
System.out.println("Go!");Custom Increment
for (
int number = 2;
number <= 20;
number += 2
) {
System.out.println(number);
}Multiple Variables in for
for (
int left = 1, right = 10;
left <= right;
left++, right--
) {
System.out.println(
left + " - " + right
);
}Omitting for Components
int number = 1;
for (
;
number <= 5;
number++
) {
System.out.println(number);
}for (
int number = 1;
number <= 5;
) {
System.out.println(number);
number++;
}Infinite for Loop
for (;;) {
System.out.println(
"Running..."
);
}while vs for
USE for WHEN:
Iteration count is known
Counter controls repetition
Initialization and update belong together
USE while WHEN:
Iteration count is unknown
Loop depends on a changing condition
Loop depends on user input
Loop depends on external stateEnhanced for Loop
The enhanced for loop, also called the for-each loop, is designed to process each element of an array or iterable collection.
Enhanced for Syntax
for (
dataType element : collection
) {
// Use element
}Enhanced for with Arrays
int[] numbers = {
10, 20, 30, 40, 50
};
for (int number : numbers) {
System.out.println(number);
}Traditional vs Enhanced for
int[] numbers = {
10, 20, 30
};
for (
int index = 0;
index < numbers.length;
index++
) {
System.out.println(
numbers[index]
);
}for (int number : numbers) {
System.out.println(number);
}Limitations of Enhanced for
- It does not directly provide the current index.
- It always processes elements in the iteration order.
- It is not suitable when you need custom index movement.
- Assigning a new value to the loop variable does not replace a primitive array element.
- Use a traditional for loop when index control is required.
Nested Loops
A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for every iteration of the outer loop.
Nested Loop Syntax
for (
int outer = 1;
outer <= 3;
outer++
) {
for (
int inner = 1;
inner <= 3;
inner++
) {
// Statements
}
}How Nested Loops Work
OUTER ITERATION 1
INNER 1
INNER 2
INNER 3
OUTER ITERATION 2
INNER 1
INNER 2
INNER 3
OUTER ITERATION 3
INNER 1
INNER 2
INNER 3Multiplication Table
for (
int table = 1;
table <= 5;
table++
) {
for (
int multiplier = 1;
multiplier <= 10;
multiplier++
) {
System.out.println(
table
+ " x "
+ multiplier
+ " = "
+ (table * multiplier)
);
}
System.out.println();
}Pattern Printing
Nested loops are commonly used for pattern printing. The outer loop usually controls rows, while the inner loop controls columns or values inside each row.
Rectangle Pattern
for (
int row = 1;
row <= 4;
row++
) {
for (
int column = 1;
column <= 6;
column++
) {
System.out.print("* ");
}
System.out.println();
}* * * * * *
* * * * * *
* * * * * *
* * * * * *Right Triangle Pattern
for (
int row = 1;
row <= 5;
row++
) {
for (
int column = 1;
column <= row;
column++
) {
System.out.print("* ");
}
System.out.println();
}*
* *
* * *
* * * *
* * * * *Number Pattern
for (
int row = 1;
row <= 5;
row++
) {
for (
int number = 1;
number <= row;
number++
) {
System.out.print(
number + " "
);
}
System.out.println();
}1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Loop Control Statements
LOOP CONTROL
├── break
│ └── Terminate loop
│
├── continue
│ └── Skip current iteration
│
├── Labeled break
│ └── Exit named outer structure
│
└── Labeled continue
└── Continue named outer loopbreak Statement
The break statement immediately terminates the nearest loop or switch statement.
break Example
for (
int number = 1;
number <= 10;
number++
) {
if (number == 5) {
break;
}
System.out.println(number);
}1
2
3
4Searching with break
int[] numbers = {
10, 25, 40, 55, 70
};
int target = 40;
boolean found = false;
for (int number : numbers) {
if (number == target) {
found = true;
break;
}
}
System.out.println(
found
? "Target found"
: "Target not found"
);continue Statement
The continue statement skips the remaining statements in the current iteration and moves to the next iteration.
continue Example
for (
int number = 1;
number <= 10;
number++
) {
if (number == 5) {
continue;
}
System.out.println(number);
}Skip Even Numbers
for (
int number = 1;
number <= 20;
number++
) {
if (number % 2 == 0) {
continue;
}
System.out.println(number);
}break vs continue
break
Terminates entire loop
Execution continues after loop
continue
Skips current iteration
Loop continues with next iterationLabeled break
outerLoop:
for (
int row = 1;
row <= 3;
row++
) {
for (
int column = 1;
column <= 3;
column++
) {
if (
row == 2
&& column == 2
) {
break outerLoop;
}
System.out.println(
row + ", " + column
);
}
}Labeled continue
outerLoop:
for (
int row = 1;
row <= 3;
row++
) {
for (
int column = 1;
column <= 3;
column++
) {
if (column == 2) {
continue outerLoop;
}
System.out.println(
row + ", " + column
);
}
}- Labels can control outer loops directly.
- They can be useful in deeply nested searching logic.
- Excessive label usage can make code difficult to follow.
- Consider extracting complex nested logic into methods.
Loop Variables and Scope
for (
int number = 1;
number <= 5;
number++
) {
System.out.println(number);
}
// Invalid:
// System.out.println(number);A variable declared inside the for initialization belongs to the loop scope and cannot be accessed after the loop ends.
Off-by-One Errors
An off-by-one error occurs when a loop executes one time too many or one time too few.
for (
int number = 1;
number <= 5;
number++
) {
System.out.println(number);
}for (
int number = 1;
number < 5;
number++
) {
System.out.println(number);
}- Understand the starting value.
- Understand whether the final value should be included.
- Check whether < or <= is correct.
- Test the first and last iterations.
Infinite Loops
int number = 1;
while (number <= 5) {
System.out.println(number);
// number never changes
}int number = 1;
while (number <= 5) {
System.out.println(number);
number--;
}Counter-Controlled Loops
for (
int count = 1;
count <= 10;
count++
) {
System.out.println(
"Iteration " + count
);
}Condition-Controlled Loops
double balance = 1000;
while (balance > 0) {
balance -= 100;
System.out.println(
"Balance: " + balance
);
}Sentinel-Controlled Loops
Scanner scanner =
new Scanner(System.in);
int value;
while (true) {
System.out.print(
"Enter value (-1 to stop): "
);
value =
scanner.nextInt();
if (value == -1) {
break;
}
System.out.println(
"You entered: " + value
);
}Accumulator Pattern
An accumulator stores a running result that is updated during each loop iteration.
int total = 0;
for (
int number = 1;
number <= 5;
number++
) {
total += number;
}
System.out.println(total);Running Total
int[] values = {
10, 20, 30, 40
};
int total = 0;
for (int value : values) {
total += value;
}
System.out.println(
"Total: " + total
);Product Accumulator
int product = 1;
for (
int number = 1;
number <= 5;
number++
) {
product *= number;
}
System.out.println(product);Finding Maximum
int[] numbers = {
45, 12, 89, 34, 67
};
int maximum = numbers[0];
for (int number : numbers) {
if (number > maximum) {
maximum = number;
}
}
System.out.println(
"Maximum: " + maximum
);Finding Minimum
int[] numbers = {
45, 12, 89, 34, 67
};
int minimum = numbers[0];
for (int number : numbers) {
if (number < minimum) {
minimum = number;
}
}
System.out.println(
"Minimum: " + minimum
);Counting Matches
int[] numbers = {
10, 15, 20, 25, 30
};
int count = 0;
for (int number : numbers) {
if (number % 2 == 0) {
count++;
}
}
System.out.println(
"Even numbers: " + count
);Factorial Program
int number = 5;
long factorial = 1;
for (
int value = 1;
value <= number;
value++
) {
factorial *= value;
}
System.out.println(
number
+ "! = "
+ factorial
);5! = 120Multiplication Table Program
int number = 7;
for (
int multiplier = 1;
multiplier <= 10;
multiplier++
) {
System.out.println(
number
+ " x "
+ multiplier
+ " = "
+ (number * multiplier)
);
}Reverse a Number
int number = 12345;
int reversed = 0;
while (number != 0) {
int digit =
number % 10;
reversed =
reversed * 10 + digit;
number /= 10;
}
System.out.println(
"Reversed: " + reversed
);Sum of Digits
int number = 5832;
int sum = 0;
while (number != 0) {
int digit =
number % 10;
sum += digit;
number /= 10;
}
System.out.println(
"Sum: " + sum
);Count Digits
int number = 987654;
int count = 0;
while (number != 0) {
number /= 10;
count++;
}
System.out.println(
"Digits: " + count
);- The number 0 contains one digit.
- A loop using while (number != 0) executes zero times for zero.
- Handle zero separately when counting digits.
Palindrome Number
int number = 12321;
int original = number;
int reversed = 0;
while (number != 0) {
int digit =
number % 10;
reversed =
reversed * 10 + digit;
number /= 10;
}
if (original == reversed) {
System.out.println(
"Palindrome"
);
} else {
System.out.println(
"Not a palindrome"
);
}Prime Number Check
int number = 29;
boolean prime = number > 1;
for (
int divisor = 2;
divisor * divisor <= number;
divisor++
) {
if (number % divisor == 0) {
prime = false;
break;
}
}
System.out.println(
prime
? "Prime number"
: "Not a prime number"
);Fibonacci Series
int first = 0;
int second = 1;
for (
int count = 1;
count <= 10;
count++
) {
System.out.print(
first + " "
);
int next =
first + second;
first = second;
second = next;
}0 1 1 2 3 5 8 13 21 34GCD Program
int first = 48;
int second = 18;
while (second != 0) {
int remainder =
first % second;
first = second;
second = remainder;
}
System.out.println(
"GCD: " + first
);Guessing Game
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int secretNumber = 7;
int guess;
int attempts = 0;
do {
System.out.print(
"Guess the number: "
);
guess =
scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println(
"Too low"
);
} else if (
guess > secretNumber
) {
System.out.println(
"Too high"
);
}
} while (
guess != secretNumber
);
System.out.println(
"Correct in "
+ attempts
+ " attempts!"
);
}
}Menu-Driven Calculator
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int choice;
do {
System.out.println(
"1. Add"
);
System.out.println(
"2. Subtract"
);
System.out.println(
"3. Multiply"
);
System.out.println(
"4. Divide"
);
System.out.println(
"5. Exit"
);
System.out.print(
"Enter choice: "
);
choice =
scanner.nextInt();
if (choice >= 1 && choice <= 4) {
System.out.print(
"Enter first number: "
);
double first =
scanner.nextDouble();
System.out.print(
"Enter second number: "
);
double second =
scanner.nextDouble();
switch (choice) {
case 1 ->
System.out.println(
first + second
);
case 2 ->
System.out.println(
first - second
);
case 3 ->
System.out.println(
first * second
);
case 4 -> {
if (second != 0) {
System.out.println(
first / second
);
} else {
System.out.println(
"Cannot divide by zero"
);
}
}
}
} else if (choice != 5) {
System.out.println(
"Invalid choice"
);
}
} while (choice != 5);
System.out.println(
"Calculator closed."
);
}
}Common Loop Errors
LOOP ERRORS
├── Missing Update
├── Wrong Update Direction
├── Incorrect Condition
├── Off-by-One Error
├── Accidental Infinite Loop
├── Semicolon after Loop Header
├── Updating Wrong Variable
├── Resetting Accumulator inside Loop
├── Incorrect Initial Value
├── Incorrect Boundary Operator
├── Modifying Loop Counter Unexpectedly
├── Forgetting break
├── Misusing continue
├── Infinite Input Loop
├── Incorrect Sentinel Handling
├── Array Index Out of Bounds
├── Excessive Nested Loops
├── Confusing while with do-while
├── Expecting do-while to Skip First Execution
├── Expecting Enhanced for to Provide Index
├── Modifying Primitive Array through for-each Variable
├── Using break When continue is Needed
├── Using continue When break is Needed
└── Failing to Test Boundary Iterationsfor (
int number = 1;
number <= 5;
number++
);
{
System.out.println(
"This is not the loop body"
);
}Best Practices
- Choose the loop type that best matches the problem.
- Use for when the number of iterations is known.
- Use while when repetition depends on a condition.
- Use do-while when the body must execute at least once.
- Use enhanced for when processing every element without needing an index.
- Use meaningful loop variable names.
- Use index for array positions.
- Use count for counting iterations.
- Use row and column for grid-based loops.
- Initialize loop variables correctly.
- Write clear termination conditions.
- Ensure the loop state changes toward termination.
- Verify update direction.
- Check whether ++ or -- is required.
- Use += for larger increments.
- Use -= for larger decrements.
- Avoid changing the loop counter unexpectedly inside the body.
- Use braces consistently.
- Indent nested loops clearly.
- Keep loop bodies focused.
- Avoid very large loop bodies.
- Extract complex repeated logic into methods.
- Avoid unnecessary nested loops.
- Consider performance when loops process large datasets.
- Use break when the required result has been found.
- Use continue when only the current iteration should be skipped.
- Do not overuse break and continue.
- Use labels only when they genuinely simplify nested control flow.
- Avoid complex labeled control flow.
- Use boolean flags when they make termination clearer.
- Use sentinel values that cannot be confused with valid input.
- Document unusual sentinel values.
- Validate user input.
- Handle invalid input without creating infinite loops.
- Test zero iterations.
- Test exactly one iteration.
- Test multiple iterations.
- Test the first boundary.
- Test the last boundary.
- Test values just outside boundaries.
- Watch for off-by-one errors.
- Use < when the upper boundary is excluded.
- Use <= when the upper boundary is included.
- Remember that array indexes start at zero.
- Use index < array.length when traversing arrays.
- Never use index <= array.length for normal array traversal.
- Initialize sum accumulators to zero.
- Initialize product accumulators to one.
- Initialize maximum and minimum values carefully.
- Use the first actual element when possible for maximum and minimum.
- Do not reset accumulators inside the loop accidentally.
- Preserve original values when a loop modifies a number.
- Handle zero separately in digit-processing algorithms when necessary.
- Consider negative numbers in numeric algorithms.
- Use long when factorial values may exceed int range.
- Understand that even long factorials overflow eventually.
- Use efficient conditions for prime checking.
- Stop searching once a result is found.
- Avoid repeated calculations inside loop conditions when unnecessary.
- Prefer readable code over clever compact loops.
- Use blank lines to separate major loop steps.
- Comment why a complex loop exists.
- Do not comment obvious increments unnecessarily.
- Use enhanced for loops for read-only element processing.
- Use traditional for loops when indexes are required.
- Use while true with break only when it makes the termination logic clearer.
- Always make intentional infinite loops obvious.
- Avoid accidental infinite loops.
- Review every loop for a guaranteed termination path.
- Test loops with realistic data sizes.
- Consider algorithm complexity for nested loops.
- Remember that two nested loops can significantly increase work.
- Use appropriate data structures to avoid unnecessary looping.
- Keep user interface logic separate from complex processing when applications grow.
- Write loops that are easy to understand and maintain.
Loop Selection Guide
KNOWN NUMBER OF ITERATIONS?
│
├── YES ─────► for
│
└── NO
│
▼
MUST BODY EXECUTE AT LEAST ONCE?
│
├── YES ─────► do-while
│
└── NO ──────► while
PROCESS EVERY ARRAY OR COLLECTION ELEMENT?
│
├── NEED INDEX ─────► for
│
└── NO INDEX NEEDED ─► enhanced forLoop Checklist
LOOP CHECKLIST
[ ] Correct loop type selected
[ ] Initialization is correct
[ ] Condition is correct
[ ] Update is correct
[ ] Update moves toward termination
[ ] Loop can terminate
[ ] First iteration tested
[ ] Last iteration tested
[ ] Zero iterations considered
[ ] One iteration considered
[ ] Boundary values tested
[ ] < and <= checked carefully
[ ] No accidental semicolon
[ ] Counter not modified unexpectedly
[ ] Accumulator initialized correctly
[ ] Accumulator not reset inside loop
[ ] Sentinel value is clear
[ ] Invalid input is handled
[ ] break is used correctly
[ ] continue is used correctly
[ ] Nested loops are necessary
[ ] Labels are genuinely useful
[ ] Array boundaries are safe
[ ] Enhanced for is suitable
[ ] Original values preserved when needed
[ ] Zero handled in digit algorithms
[ ] Negative values considered
[ ] Infinite loop is intentional
[ ] Loop body remains readable
[ ] Performance is acceptable
[ ] Every termination path is understoodCommon Misconceptions
- A loop does not automatically terminate unless its condition eventually becomes false or control exits it.
- A while loop may execute zero times.
- A for loop may execute zero times.
- A do-while loop always executes at least once.
- The semicolon after a do-while condition is required.
- A semicolon after a while or for header usually creates an empty loop body.
- The update expression in a for loop runs after the body.
- The initialization section of a for loop runs only once.
- Multiple variables can be initialized in one for loop when they share a compatible declaration structure.
- A for loop does not have to increment by one.
- A for loop can count backward.
- A for loop can omit initialization, condition, or update sections.
- for (;;) creates an infinite loop.
- break terminates the loop.
- continue does not terminate the loop.
- continue skips only the remaining work in the current iteration.
- A break inside a nested loop normally exits only the nearest loop.
- Labels can target outer loops.
- Enhanced for loops do not directly expose indexes.
- Changing a primitive enhanced-for variable does not modify the original array element.
- Nested loops multiply the amount of repeated work.
- Off-by-one errors are boundary errors.
- An accumulator for addition normally starts at zero.
- An accumulator for multiplication normally starts at one.
- The original number may need to be saved before digit-processing loops modify it.
- Zero requires special handling in some digit-counting algorithms.
- A prime number must be greater than one.
- Loops are not always the best solution for every repeated-looking problem.
- Shorter loop code is not automatically clearer.
- Infinite loops can be intentional.
- Every loop should have an understood termination strategy.
Practice Exercises
- Print numbers from 1 to 100.
- Solve using while.
- Solve using do-while.
- Solve using for.
- Print all even numbers from 1 to 100.
- Create one solution using a condition.
- Create another solution using an increment of 2.
- Read a number from the user.
- Print its multiplication table from 1 to 10.
- Use a for loop.
- Read a positive number n.
- Calculate the sum from 1 to n.
- Use an accumulator.
- Reject negative input.
- Read a non-negative integer.
- Calculate its factorial.
- Remember that 0! equals 1.
- Use long for the result.
- Read an integer.
- Reverse its digits.
- Display the reversed number.
- Read a number.
- Preserve the original value.
- Reverse the number.
- Compare the original and reversed values.
- Read an integer.
- Check whether it is greater than one.
- Search for a divisor.
- Stop early when a divisor is found.
- Read the number of terms.
- Generate the Fibonacci sequence.
- Handle zero or negative term counts.
- Print a rectangle.
- Print a right triangle.
- Print an inverted triangle.
- Print a number triangle.
- Use nested loops.
Common Interview Questions
What is a loop?
A loop repeatedly executes a block of code while a condition remains true or until another termination condition is reached.
What loop types are available in Java?
Java provides while, do-while, for, and enhanced for loops.
What is the difference between while and do-while?
while checks the condition before the body, while do-while checks it after the body and therefore executes at least once.
When should a for loop be used?
A for loop is commonly used when repetition is controlled by a counter or the number of iterations is known.
What is an enhanced for loop?
It is a loop designed to process each element of an array or iterable collection without manually managing an index.
What is an infinite loop?
An infinite loop is a loop whose termination condition never becomes false or is never reached.
What does break do?
break immediately terminates the nearest loop or switch statement.
What does continue do?
continue skips the remaining statements in the current iteration and proceeds to the next iteration.
What is an off-by-one error?
It is an error where a loop executes one iteration too many or one iteration too few.
What is a nested loop?
A nested loop is a loop placed inside another loop.
What is a sentinel value?
A sentinel is a special value used to signal that repeated input or processing should stop.
What is an accumulator?
An accumulator stores a running result that is updated during loop iterations.
Can a for loop have multiple variables?
Yes. Multiple variables can be initialized and updated in a for loop.
Can parts of a for loop be omitted?
Yes. Initialization, condition, and update sections may be omitted, although the semicolons remain required.
What does for (;;) mean?
It creates an infinite for loop.
Frequently Asked Questions
Which loop should beginners use first?
Learn all loop types. Use for for known repetition counts, while for condition-based repetition, and do-while when the body must run at least once.
Can a while loop execute zero times?
Yes. If its initial condition is false, the body is skipped.
Can a do-while loop execute zero times?
No. Its body always executes at least once.
Can I use break inside any loop?
Yes. break can terminate while, do-while, and for loops.
Does continue stop the loop?
No. It skips the rest of the current iteration and continues with the next iteration.
Why is my loop running forever?
The condition may always remain true, the loop variable may not be updated, or the update may move in the wrong direction.
Should I always use enhanced for with arrays?
No. Use it when you only need each value. Use a traditional for loop when you need indexes or custom traversal.
Are nested loops bad?
No, but they increase repeated work. Use them when the problem naturally requires multiple dimensions or combinations.
What should I learn after loops?
The next lesson covers methods in Java.
Key Takeaways
- Loops repeat blocks of code.
- Loops reduce code duplication.
- Every loop needs a clear repetition rule.
- Initialization establishes the starting state.
- The condition determines whether repetition continues.
- The loop body contains repeated work.
- The update changes loop state.
- while is an entry-controlled loop.
- A while loop may execute zero times.
- do-while is an exit-controlled loop.
- A do-while loop always executes at least once.
- The semicolon after a do-while condition is required.
- for is commonly used for counter-controlled repetition.
- A for loop combines initialization, condition, and update.
- Initialization runs once.
- The condition is checked before each iteration.
- The update runs after each iteration.
- A for loop can count forward.
- A for loop can count backward.
- A for loop can use custom increments.
- A for loop can manage multiple variables.
- for (;;) creates an infinite loop.
- Enhanced for processes array or collection elements.
- Enhanced for does not directly provide an index.
- Traditional for is better when index control is needed.
- Nested loops place one loop inside another.
- The inner loop completes for each outer iteration.
- Nested loops are useful for tables and patterns.
- break terminates a loop.
- continue skips the current iteration.
- Labeled break can exit an outer loop.
- Labeled continue can continue an outer loop.
- Labels should be used carefully.
- Loop variables have scope.
- Variables declared in a for header usually belong to the loop scope.
- Off-by-one errors affect loop boundaries.
- < and <= produce different iteration counts.
- Infinite loops may be intentional or accidental.
- Missing updates commonly cause infinite loops.
- Wrong update direction can cause infinite loops.
- Counter-controlled loops repeat a known number of times.
- Condition-controlled loops depend on changing state.
- Sentinel-controlled loops stop on a special value.
- Accumulators store running results.
- Sum accumulators usually start at zero.
- Product accumulators usually start at one.
- Loops can find maximum and minimum values.
- Loops can count matching values.
- Loops can calculate factorials.
- Loops can process digits.
- Loops can reverse numbers.
- Loops can calculate digit sums.
- Loops can check palindrome numbers.
- Loops can test prime numbers.
- Loops can generate Fibonacci sequences.
- Loops can build interactive menus.
- Input validation commonly uses loops.
- Every loop should have an understood termination path.
- Boundary testing is essential.
- Readable loops are easier to maintain.
- The correct loop depends on the problem.
Summary
Loops allow Java programs to repeat operations efficiently without duplicating code. They are essential for processing data, validating input, performing calculations, building menus, and implementing repeated application behavior.
The while loop checks its condition before execution and is useful when the number of iterations is unknown. The do-while loop checks its condition after execution and therefore always runs at least once.
The for loop is ideal for counter-controlled repetition because initialization, condition, and update are written together. The enhanced for loop provides a simpler way to process every element of an array or iterable collection.
Nested loops allow repeated operations within repeated operations and are commonly used for tables, grids, combinations, and pattern printing.
The break statement terminates a loop immediately, while continue skips the remaining work in the current iteration. Labeled versions can control outer loops but should be used carefully.
Correct initialization, conditions, updates, and boundaries are essential. Missing updates, incorrect operators, wrong update directions, and off-by-one errors are among the most common loop problems.
Loops support important programming patterns including counters, sentinels, accumulators, searching, maximum and minimum calculations, digit processing, factorials, prime checking, and sequence generation.
Choosing the correct loop structure and writing a clear termination condition makes Java programs safer, easier to understand, and easier to maintain.
- You understand what loops are.
- You understand why repetition is needed.
- You understand how loops work.
- You understand loop components.
- You know the main Java loop types.
- You understand entry-controlled loops.
- You understand exit-controlled loops.
- You can use while loops.
- You understand while syntax.
- You can count forward with while.
- You can count backward with while.
- You can use while with user input.
- You understand sentinel-controlled loops.
- You can calculate sums with while.
- You understand infinite while loops.
- You can use do-while loops.
- You understand do-while syntax.
- You understand why do-while executes at least once.
- You can compare while and do-while.
- You can build menus with do-while.
- You can validate input with loops.
- You can use for loops.
- You understand for syntax.
- You understand for execution order.
- You can count forward and backward with for.
- You can use custom increments.
- You can use multiple for variables.
- You understand omitted for components.
- You understand infinite for loops.
- You can compare while and for.
- You can use enhanced for loops.
- You can process arrays with enhanced for.
- You can compare traditional and enhanced for loops.
- You understand enhanced for limitations.
- You can use nested loops.
- You understand nested loop execution.
- You can generate multiplication tables.
- You can print patterns.
- You can use break.
- You can search efficiently with break.
- You can use continue.
- You can compare break and continue.
- You understand labeled break.
- You understand labeled continue.
- You understand loop variable scope.
- You understand off-by-one errors.
- You can identify infinite loops.
- You understand counter-controlled loops.
- You understand condition-controlled loops.
- You understand sentinel-controlled loops.
- You understand accumulator patterns.
- You can calculate running totals.
- You can calculate products.
- You can find maximum values.
- You can find minimum values.
- You can count matching values.
- You can calculate factorials.
- You can generate multiplication tables.
- You can reverse numbers.
- You can calculate digit sums.
- You can count digits.
- You can check palindrome numbers.
- You can check prime numbers.
- You can generate Fibonacci sequences.
- You can calculate GCD.
- You can build a guessing game.
- You can build a menu-driven calculator.
- You can identify common loop errors.
- You know loop best practices.
- You know how to choose the correct loop.
- You are ready to learn methods.