java

Loops


Comparison of Loops

Featurefor Loopwhile Loopdo-while LoopEnhanced for Loop
Condition CheckBefore each iterationBefore each iterationAfter each iterationN/A (Iterates through each element)
UsageKnown number of iterationsUnknown iterations with a conditionAt least one execution is requiredIterating over arrays/collections
Best ForCounting loopsConditional loopsLoops requiring at least one passArrays/Collections

1. What Are Loops?

Loops are control structures that allow a block of code to be executed repeatedly until a specified condition is met.


2. Types of Loops in Java

  1. for Loop
  2. while Loop
  3. do-while Loop
  4. Enhanced for Loop (for-each Loop)

3. for Loop

The for loop is used when the number of iterations is known beforehand.

Syntax

Example

Working

  1. Initialization: Executes once before the loop starts (e.g., int i = 1).
  2. Condition: Checked before each iteration. If true, the loop runs; if false, the loop exits.
  3. Update: Executes after each iteration (e.g., i++).

4. while Loop

The while loop is used when the number of iterations is not known and depends on a condition.

Syntax

Example

Working

  1. The condition is checked before each iteration.
  2. If the condition is true, the loop body executes.
  3. If the condition is false, the loop terminates.

5. do-while Loop

The do-while loop is similar to the while loop, but it ensures that the loop body executes at least once before the condition is checked.

Syntax

Example

Working

  1. Executes the loop body first.
  2. Then checks the condition.
  3. Repeats the process if the condition is true.

6. Enhanced for Loop (for-each Loop)

The enhanced for loop is used to iterate over arrays or collections.

Syntax

Example

Working

  1. Iterates through each element in the array or collection.
  2. Assigns each element to the loop variable (num in the example).

Control Statements in Loops

Java provides additional control statements to manage the flow of loops:

1. break

  • Terminates the loop immediately.

2. continue

  • Skips the current iteration and moves to the next one.

3. return

  • Exits from the current method entirely, stopping all loops.

Examples of Nested Loops

Loops can be nested inside one another for multidimensional iterations.

Example: Nested for Loop

Output:


Infinite Loops

An infinite loop occurs when the termination condition is never met.

Example

Use break to terminate infinite loops when needed.


Best Practices for Loops

  1. Avoid Infinite Loops: Ensure the condition eventually becomes false.
  2. Optimize Performance: Minimize operations inside the loop.
  3. Use Enhanced for: When iterating over arrays/collections.
  4. Clear Conditions: Ensure loop conditions are readable and maintainable.

Leave a Reply

Your email address will not be published. Required fields are marked *