Java Full Course: Mastering the Language Loops in Java

Loops in Java

(Complete Notes | Beginner to Advanced | Professional & Exam-Oriented | Masterclass)

1. Introduction to Looping

In programming, we often need to execute a block of code multiple times—whether it's processing items in an array, reading input until a condition is met, or repeatedly performing a calculation. This repeated execution is called looping (or iteration). Java provides several loop constructs that allow you to control how many times a block of code runs:

  • while loop – repeats a block as long as a condition remains true; the condition is checked before each iteration.
  • do-while loop – similar to while, but guarantees at least one execution because the condition is checked after the loop body.
  • for loop – ideal when the number of iterations is known in advance; combines initialization, condition, and update in a single line.
  • Enhanced for loop (for-each) – simplifies iteration over arrays and collections, focusing on the elements rather than the index.

Looping constructs are fundamental to writing efficient, concise, and maintainable code. They allow you to avoid repetitive code and handle dynamic data sets gracefully.

In the following sections, we will explore each loop type in detail, covering syntax, flow, common use cases, and best practices.


2. The while Loop

The while loop is a fundamental iterative construct that repeatedly executes a block of code as long as a specified condition remains true. It is an entry controlled loop, meaning the condition is evaluated before each iteration. If the condition is false initially, the loop body is never executed.


2.1 Syntax

while (condition) { // loop body: statements to repeat }
  • condition – a boolean expression. The loop continues as long as this evaluates to true.
  • The loop body can be a single statement or a block enclosed in curly braces {}. Using braces is recommended even for a single statement.
  • The loop will terminate when the condition becomes false.

2.2 Flow of Control

Start | v condition? / \ true/ \false / \ v v loop body exit loop | | +-----------+ (back to condition check) | v next statement

Key points:

  • Condition checked first.
  • If true, loop body executes, then condition checked again.
  • If false, loop ends and control passes to the next statement after the loop.

2.3 Basic Example

int count = 1; while (count <= 5) { System.out.println("Count: " + count); count++; } System.out.println("Loop finished.");

Output:

Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Loop finished.

2.4 Infinite Loop

If the condition never becomes false, the loop runs forever (or until the program is terminated). This is often a programming error, but sometimes intentional (e.g., server loops).

while (true) { // runs forever unless break is used }

To exit an infinite loop, use a break statement or a return.


2.5 Common Use Cases

a) Iterating with a Counter

int i = 0; while (i < 10) { System.out.println(i); i++; }

b) Reading Input Until Sentinel

Scanner sc = new Scanner(System.in); int input; while ((input = sc.nextInt()) != -1) { System.out.println("You entered: " + input); } System.out.println("Sentinel encountered. Exiting.");

c) Validating User Input

int number; boolean valid = false; while (!valid) { System.out.print("Enter a positive number: "); number = sc.nextInt(); if (number > 0) { valid = true; System.out.println("Thank you!"); } else { System.out.println("Invalid. Try again."); } }

d) Processing Elements of a Collection (When Index Not Needed)

List<String> list = Arrays.asList("A", "B", "C"); int index = 0; while (index < list.size()) { System.out.println(list.get(index)); index++; }

2.6 Common Pitfalls

a) Forgetting to Update the Condition Variable

int i = 0; while (i < 5) { System.out.println(i); // i++ missing -> infinite loop }

b) Off by One Errors

int i = 1; while (i < 5) { // runs for i = 1,2,3,4 (4 times) System.out.println(i); i++; }

Always verify the loop's initial value and condition to ensure the correct number of iterations.

c) Using = Instead of == in Condition

boolean flag = false; while (flag = true) { // assignment, always true -> infinite loop // ... }

Use == for comparison, or simply while (flag).

d) Semicolon After Condition

int i = 0; while (i < 5); { // semicolon terminates the loop; the block is NOT part of the loop System.out.println(i); i++; }

The semicolon creates an empty body; the loop spins forever (or until condition false) doing nothing. The following block executes only once after the loop.


2.7 Nested while Loops

A while loop can contain another loop inside its body.

int i = 1; while (i <= 3) { int j = 1; while (j <= 3) { System.out.print("* "); j++; } System.out.println(); i++; }

Output:

* * * * * * * * *

2.8 break and continue in while

  • break – exits the loop immediately.
  • continue – skips the rest of the current iteration and jumps to the condition check.
int i = 0; while (i < 10) { i++; if (i % 2 == 0) { continue; // skip printing even numbers } System.out.println(i); } // Output: 1 3 5 7 9
while (true) { int input = sc.nextInt(); if (input == 0) { break; // exit when 0 is entered } System.out.println("You entered: " + input); }

2.9 Performance Considerations

  • The while loop is as efficient as other loops; the main overhead is the condition evaluation.
  • Avoid placing expensive operations inside the condition unless necessary.
  • For large loops, keep the loop body concise and avoid unnecessary method calls.

2.10 Best Practices

  • Always use braces {} even for single statements to prevent errors when adding more code.
  • Ensure loop termination – the loop should eventually make the condition false. Use a counter or a flag that changes inside the loop.
  • Avoid complex conditions – store complex boolean logic in a variable for readability.
  • Use while when the number of iterations is not known beforehand and depends on dynamic conditions.
  • Prefer for loop when iterating a fixed number of times (e.g., arrays with indices) for clarity.
  • Minimize the scope of variables used only in the loop; declare them just before the loop or inside the loop body as needed.

2.11 Examples

Example 1: Sum of digits

int num = 12345; int sum = 0; while (num > 0) { sum += num % 10; num /= 10; } System.out.println("Sum of digits: " + sum);

Example 2: Reversing a number

int num = 12345; int reversed = 0; while (num != 0) { reversed = reversed * 10 + num % 10; num /= 10; } System.out.println("Reversed: " + reversed);

Example 3: Simple menu system

Scanner sc = new Scanner(System.in); int choice = 0; while (choice != 3) { System.out.println("1. Option A"); System.out.println("2. Option B"); System.out.println("3. Exit"); System.out.print("Choose: "); choice = sc.nextInt(); switch (choice) { case 1: System.out.println("You chose A"); break; case 2: System.out.println("You chose B"); break; case 3: System.out.println("Goodbye!"); break; default: System.out.println("Invalid choice"); } }

2.12 Key Points to Remember

  • while is an entry controlled loop; condition is evaluated before each iteration.
  • The loop may never execute if the condition starts as false.
  • Ensure the loop condition eventually becomes false to avoid infinite loops.
  • Use break to exit early, continue to skip the remainder of an iteration.
  • For counters or index based iteration, a for loop is often more concise.
  • Always use braces {} to define the loop body clearly.

3. The do-while Loop

The do-while loop is a post test (exit controlled) loop: it executes the loop body at least once, then checks the condition. If the condition remains true, the loop repeats; otherwise, it terminates. This makes it ideal for scenarios where you need to ensure the loop body runs before evaluating a termination condition.


3.1 Syntax

do { // loop body: statements to repeat } while (condition);
  • The loop body is executed first.
  • After the body, the condition (a boolean expression) is evaluated.
  • If condition is true, the loop repeats; if false, control exits the loop.
  • A semicolon ; is required after the while (condition).

3.2 Flow of Control

Start | v execute loop body | v evaluate condition / \ true/ \false / \ v v repeat exit loop | | +------------+ | v next statement

Key difference from while: the condition is evaluated after the loop body, guaranteeing at least one execution.


3.3 Basic Example

int count = 1; do { System.out.println("Count: " + count); count++; } while (count <= 5);

Output:

Count: 1 Count: 2 Count: 3 Count: 4 Count: 5

Even if count started at 6, the loop would still execute once.


3.4 When to Use do-while

Use do-while when you need the loop body to execute at least once regardless of the condition. Common scenarios:

  • Menu driven programs – show the menu first, then get user choice.
  • Input validation – prompt for input, then validate; repeat if invalid.
  • Games – run the game logic at least once, then check if the player wants to continue.

3.5 Examples

a) Simple Menu System

Scanner sc = new Scanner(System.in); int choice; do { System.out.println("1. Start Game"); System.out.println("2. Load Game"); System.out.println("3. Exit"); System.out.print("Enter your choice: "); choice = sc.nextInt(); switch (choice) { case 1 -> System.out.println("Starting game..."); case 2 -> System.out.println("Loading game..."); case 3 -> System.out.println("Goodbye!"); default -> System.out.println("Invalid choice. Try again."); } } while (choice != 3);

b) Input Validation (Repeat Until Valid)

int number; do { System.out.print("Enter a positive number: "); number = sc.nextInt(); if (number <= 0) { System.out.println("Invalid input. Must be positive."); } } while (number <= 0); System.out.println("You entered: " + number);

c) Guessing Game

int secret = new Random().nextInt(10) + 1; int guess; do { System.out.print("Guess the number (1-10): "); guess = sc.nextInt(); if (guess != secret) { System.out.println("Wrong! Try again."); } } while (guess != secret); System.out.println("Correct!");

3.6 Infinite Loop with do-while

do { // loop body } while (true);

To exit, use break or return inside the loop.


3.7 Difference Between while and do-while

Featurewhiledo-while
Condition checkAt the beginning (entry controlled)At the end (exit controlled)
Minimum executions0 (if condition initially false)1 (always executes at least once)
Semicolon afterNoYes, after while (condition);
Typical useWhen number of iterations unknown, may be zeroWhen at least one iteration is required

3.8 Common Pitfalls

a) Missing Semicolon

do { // ... } while (condition) // missing semicolon -> compilation error

b) Infinite Loop Due to Condition Not Updated

int i = 1; do { System.out.println(i); // i++ missing -> condition i <= 5 remains true forever } while (i <= 5);

c) Confusing with while Leading to Off by One

If you need zero or more iterations, use while. Using do-while when the loop should possibly run zero times will cause an extra execution.

d) Variable Scope

Variables declared inside the do block are not accessible in the while condition. Declare them before the loop if needed in the condition.

do { int x = 5; // local to block } while (x > 0); // error: cannot find symbol x

3.9 break and continue in do-while

  • break – exits the loop immediately.
  • continue – skips the rest of the current iteration and jumps to the condition evaluation (since it's a post test loop, it will check the condition next).
int i = 0; do { i++; if (i % 2 == 0) { continue; // skip printing even numbers } System.out.println(i); } while (i < 10); // Output: 1 3 5 7 9

3.10 Nested do-while Loops

do-while loops can be nested inside each other or inside other loops.

int i = 1; do { int j = 1; do { System.out.print("* "); j++; } while (j <= i); System.out.println(); i++; } while (i <= 5);

Output:

* * * * * * * * * * * * * * *

3.11 Best Practices

  • Use do-while when the loop must execute at least once – for menus, input prompts, and validation.
  • Always use braces {} for the loop body, even for a single statement.
  • Declare loop control variables outside the loop if they are needed in the condition.
  • Keep the loop body concise; extract complex logic into methods.
  • Avoid infinite loops – ensure the condition eventually becomes false or provide an exit via break.
  • Prefer while for zero or more iterations; use do-while only when a first execution is mandatory.

3.12 Performance Considerations

  • do-while has the same performance characteristics as while.
  • For large loops, avoid expensive operations inside the condition or the loop body.

3.13 Key Points to Remember

  • do-while guarantees at least one execution of the loop body.
  • Condition is checked after the body; a semicolon follows the while(condition);.
  • Use it for scenarios like menus, input validation, or any process that must run once before checking termination.
  • Variables declared inside the do block are not visible in the condition.
  • Be mindful of infinite loops; update the condition variable inside the body.
  • break exits the loop; continue skips to the condition check.

4. The for Loop

The for loop is a powerful iteration construct that combines initialization, condition checking, and update in a single line. It is typically used when the number of iterations is known in advance (counter controlled loops). Java provides two flavors: the traditional for loop and the enhanced for loop (for each), introduced in Java 5.


4.1 Traditional for Loop Syntax

for (initialization; condition; update) { // loop body }
  • initialization – executed once at the beginning. Usually declares and initializes a loop control variable.
  • condition – a boolean expression evaluated before each iteration. If true, the loop body executes; if false, the loop terminates.
  • update – executed after each iteration (before the next condition check). Typically increments or decrements the loop control variable.

All three parts are optional, but the semicolons are required.

Flow of Control

Start | v initialization (once) | v condition? --------false-------> exit loop | | true| | v | loop body | | | v | update | | | +-----------------------------+ | v next statement

4.2 Basic Examples

Example 1: Print numbers 1 to 5

for (int i = 1; i <= 5; i++) { System.out.println(i); }

Example 2: Sum of first 10 natural numbers

int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } System.out.println("Sum = " + sum);

Example 3: Iterating backwards

for (int i = 10; i >= 1; i--) { System.out.print(i + " "); } // Output: 10 9 8 7 6 5 4 3 2 1

4.3 Variations of the for Loop

a) Multiple Initialization and Update Expressions

You can initialize or update multiple variables using commas.

for (int i = 0, j = 10; i < j; i++, j--) { System.out.println("i = " + i + ", j = " + j); }

b) Omitting Parts

Any part can be omitted, but the semicolons remain.

  • Omitting initialization (variable declared before loop):
int i = 0; for (; i < 5; i++) { System.out.println(i); }
  • Omitting condition (creates infinite loop; use break to exit):
for (int i = 0; ; i++) { if (i > 5) break; System.out.println(i); }
  • Omitting update (update inside body):
for (int i = 0; i < 5; ) { System.out.println(i); i++; }
  • Omitting all three (infinite loop):
for (;;) { // runs forever unless break }

c) Using the Comma Operator

The comma is used to separate multiple expressions in the initialization and update sections. It is not an operator in the condition section.

for (int i = 0, j = 10; i < j; i++, j--) { System.out.println(i + " " + j); }

4.4 Scope of Loop Variable

A variable declared inside the for loop's initialization is local to the loop and cannot be accessed outside.

for (int i = 0; i < 5; i++) { // i is accessible here } // i is NOT accessible here (compilation error)

If you need the variable after the loop, declare it before the loop:

int i; for (i = 0; i < 5; i++) { // ... } System.out.println("Final i = " + i);

4.5 Common Pitfalls

a) Off by One Errors

for (int i = 0; i <= 10; i++) // runs 11 times (i = 0..10) for (int i = 0; i < 10; i++) // runs 10 times (i = 0..9)

Be careful with the condition and initial value.

b) Using = Instead of == in Condition

for (int i = 0; i = 5; i++) // compilation error (i = 5 is not boolean)

c) Modifying the Loop Variable Inside the Body

Changing the loop variable inside the body can lead to unexpected behavior.

for (int i = 0; i < 10; i++) { i = i + 2; // causes irregular iteration; usually not intended }

d) Semicolon After the Parentheses

for (int i = 0; i < 5; i++); // semicolon ends the loop; body is separate { System.out.println(i); // error: i not in scope, and this block executes once }

e) Floating Point Loop Control

Using floating point variables as loop counters can cause precision issues.

for (double d = 0.0; d != 1.0; d += 0.1) { // may never terminate System.out.println(d); }

Prefer integer counters.


4.6 Nested for Loops

A for loop can contain another loop inside its body. Nested loops are common for processing multi dimensional data.

Example: Multiplication table

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.printf("%4d", i * j); } System.out.println(); }

Output:

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

Example: Pattern printing

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } // Output: // * // * * // * * * // * * * * // * * * * *

4.7 break and continue in for Loops

  • break – terminates the loop immediately.
  • continue – skips the rest of the current iteration and jumps to the update, then condition.
// break: find first even number > 0 for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { System.out.println("First even: " + i); break; } } // continue: print odd numbers only for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } System.out.print(i + " "); } // Output: 1 3 5 7 9

In nested loops, break and continue apply only to the innermost loop unless used with labels.


4.8 Enhanced for Loop (for-each)

Introduced in Java 5, the enhanced for loop simplifies iterating over arrays and collections when you only need the elements, not the index.

Syntax

for (Type variable : iterable) { // loop body }
  • Type – the element type of the array or collection.
  • variable – takes each element value in sequence.
  • iterable – an array or an object implementing Iterable (e.g., Collection).

Examples

Array:

int[] numbers = {10, 20, 30, 40}; for (int num : numbers) { System.out.println(num); }

Collection (List):

List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); for (String name : names) { System.out.println(name); }
Crucial

[!IMPORTANT] The loop variable is a copy of the element. Modifying it does not change the original array/collection.

for (int num : numbers) { num = 0; // does not modify the array }

To modify elements, use the traditional for loop with an index.

When to Use Enhanced for

  • When you need to iterate through all elements.
  • When you do not need the index or modify the collection structure.

When to Use Traditional for

  • When you need the index.
  • When you need to modify elements (for arrays).
  • When you need to iterate over a range or with a custom step.

4.9 Performance Considerations

  • The traditional for loop and enhanced for loop have similar performance for arrays and ArrayList.
  • For linked structures (e.g., LinkedList), the enhanced for is efficient because it uses the iterator.
  • Avoid placing expensive method calls in the condition or update parts; compute once and store if possible.

4.10 Best Practices

  • Keep the loop simple – the initialization, condition, and update should be clear.
  • Use the enhanced for loop when you only need to read elements.
  • Declare loop variables inside the for to limit their scope.
  • Avoid modifying the loop variable inside the body unless absolutely necessary.
  • Use integer counters for loops to avoid floating point precision issues.
  • Use meaningful variable namesi, j, k for simple loops, but descriptive names for complex ones.
  • Prefer for over while when the number of iterations is known – it keeps all loop control logic together.

4.11 Summary Table: for Loop Features

FeatureTraditional forEnhanced for (for-each)
Syntaxfor(init; cond; update) { }for(Type var : iterable) { }
Access to indexYes (via loop variable)No
Modify elementsYes (through index)No (copy)
Use caseCounter controlled loops, range iterationIterating over all elements of array/collection
Scope of loop variableIn initialization (if declared there)Inside loop only (variable is local)
ComplexityMore flexible (multiple expressions, skip parts)Simpler, less error prone

4.12 Key Points to Remember

  • The traditional for loop combines initialization, condition, and update in one line, making it ideal for counter based iteration.
  • All three parts are optional; an empty for(;;) creates an infinite loop.
  • Variables declared in the initialization are local to the loop.
  • Use the enhanced for loop for simple read only iteration over arrays and collections.
  • Be mindful of off by one errors, modifying the loop variable, and using floating point counters.
  • break and continue work in for loops as in other loops.
  • Nested for loops are common for working with multi dimensional data.

5. Nested Loops

A nested loop is a loop inside the body of another loop. The outer loop controls how many times the inner loop executes. Nested loops are essential for processing multi dimensional data (like matrices), generating patterns, and performing complex iterative tasks.


5.1 Basic Concept

When a loop contains another loop, the inner loop completes all its iterations for each iteration of the outer loop.

for (int i = 1; i <= 3; i++) { // outer loop for (int j = 1; j <= 2; j++) { // inner loop System.out.println("i=" + i + ", j=" + j); } }

Output:

i=1, j=1 i=1, j=2 i=2, j=1 i=2, j=2 i=3, j=1 i=3, j=2
  • Outer loop runs 3 times.
  • For each outer iteration, the inner loop runs 2 times.
  • Total iterations: 3 × 2 = 6.

5.2 Types of Nested Loops

You can nest any combination of loop types: for, while, do-while.

a) for inside for (most common)

for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { System.out.print("* "); } System.out.println(); }

b) while inside for

for (int i = 1; i <= 5; i++) { int j = 1; while (j <= i) { System.out.print("* "); j++; } System.out.println(); }

c) do-while inside for

for (int i = 1; i <= 3; i++) { int j = 1; do { System.out.print(j + " "); j++; } while (j <= i); System.out.println(); }

d) Any combination (e.g., while inside while)

int i = 1; while (i <= 5) { int j = 1; while (j <= i) { System.out.print("* "); j++; } System.out.println(); i++; }

5.3 Common Use Cases

a) Multiplication Table

for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { System.out.printf("%4d", i * j); } System.out.println(); }

b) Pattern Printing (Triangle)

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); }
* * * * * * * * * * * * * * *

c) Inverted Triangle

for (int i = 5; i >= 1; i--) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); }

d) Matrix Operations (Sum, Transpose, Multiplication)

int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Sum of all elements int sum = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } } System.out.println("Sum = " + sum);

e) Finding Prime Numbers (Sieve of Eratosthenes style)

boolean[] isPrime = new boolean[100]; Arrays.fill(isPrime, true); for (int i = 2; i < 100; i++) { if (isPrime[i]) { for (int j = i * i; j < 100; j += i) { isPrime[j] = false; } } }

5.4 Controlling Nested Loops: break and continue

By default, break and continue affect only the innermost loop.

for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { break; // exits inner loop only } System.out.println(i + "," + j); } }

To break out of an outer loop, use labeled breaks or a flag.

a) Labeled break

outerLoop: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { break outerLoop; // exits both loops } System.out.println(i + "," + j); } }

b) Labeled continue

outerLoop: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { continue outerLoop; // skips to next outer iteration } System.out.println(i + "," + j); } }

5.5 Performance Considerations

  • Nested loops multiply complexity: if outer loop runs n times and inner runs m times, total operations = n × m.
  • Avoid deep nesting (more than 2 or 3 levels) for readability and performance.
  • Move invariant computations out of the inner loop (e.g., compute a constant value before the inner loop).
  • For large data, consider alternative algorithms (e.g., using Stream or specialised data structures).

Example of optimizing invariant:

// Inefficient: re-computes innerBound for every j for (int i = 0; i < n; i++) { for (int j = 0; j < someComplexCalculation(i); j++) { // ... } } // Better: compute once for (int i = 0; i < n; i++) { int limit = someComplexCalculation(i); for (int j = 0; j < limit; j++) { // ... } }

5.6 Common Pitfalls

a) Variable Scope

Variables declared inside the inner loop are local and cannot be used outside.

b) Confusing Loop Counts

for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { // this runs 25 times } }

Be mindful of the total number of iterations; an inner loop that runs many times can cause performance issues.

c) Using the Same Variable Name in Nested Loops

While allowed, it can be confusing. Use distinct names (i, j, k) or meaningful names (row, col).

d) Off by One in Boundaries

Especially when processing arrays, ensure indices stay within bounds.

e) Unintended Infinite Loops

If the inner loop modifies the outer loop's control variable, you may get unexpected infinite loops.


5.7 Best Practices

  • Use meaningful variable names for nested loops, especially when more than two levels. For simple counters, i, j, k are acceptable.
  • Limit nesting depth – refactor deeply nested loops into separate methods when possible.
  • Use labels sparingly; they can make code harder to follow. Often a flag or a method return is clearer.
  • Keep the inner loop body concise – if it becomes long, extract it into a method.
  • Consider enhanced for for iterating over collections and arrays without indices when you don't need the index.

5.8 Advanced: Nested Loops with Different Iteration Patterns

You can have loops with different step sizes, or where the inner loop's range depends on the outer loop's index.

for (int i = 0; i < 5; i++) { for (int j = i; j < 5; j++) { // triangular pattern System.out.print("* "); } System.out.println(); } // Output: // * * * * * // * * * * // * * * // * * // *

5.9 Examples in Real Applications

  • Image processing: iterating over pixels in a 2D image (rows and columns).
  • Game development: checking collisions between objects in a grid.
  • Database operations: processing result sets and related sub records.
  • Sorting algorithms: nested loops in bubble sort, insertion sort, etc.

5.10 Summary

  • A nested loop is a loop inside another loop.
  • The inner loop completes all its iterations for each iteration of the outer loop.
  • Any combination of loop types (for, while, do-while) can be nested.
  • Nested loops are used for multi dimensional data, pattern generation, and complex iterations.
  • Use labels only when necessary to break/continue outer loops.
  • Keep nesting depth manageable for readability and performance.
  • Be cautious about total iteration count and off by one errors.

Hi! Need help with studies? 👋
AI