Examples of Infinite Loop Examples

Discover practical examples of infinite loops and learn how to identify and debug them effectively.
By Jamie

Understanding Infinite Loops

Infinite loops are a common runtime error that can occur in programming when a loop runs indefinitely due to a condition that is always true or never properly updated. These loops can lead to application crashes or unresponsive programs, making it crucial for developers to recognize and debug them. Here are three diverse examples of infinite loops:

Example 1: Basic While Loop

Context: A simple while loop intended to count from 1 to 5.

In this example, a while loop is set up to count, but the condition never changes, resulting in an infinite loop:

count = 1
while count <= 5:
    print(count)

The loop is supposed to print numbers 1 through 5, but since the variable count is never incremented, it will continuously print 1 indefinitely. To fix this, you should increment the count variable within the loop:

count = 1
while count <= 5:
    print(count)
    count += 1  # Increment count to avoid infinite loop

Notes:

  • Always ensure that the loop’s terminating condition will eventually be met.
  • Testing edge cases can help identify potential infinite loops early in development.

Example 2: For Loop with Incorrect Range

Context: Using a for loop to iterate through a list.

This example uses a for loop incorrectly, which inadvertently creates an infinite loop:

let i = 0;
for (; i < 10;) {
    console.log(i);
    // Missing increment for i
}

The loop intends to log numbers from 0 to 9, but because the increment statement is missing, it continues printing 0 forever. To correct it, you should include an increment statement in the for loop:

let i = 0;
for (; i < 10; i++) {
    console.log(i);  // Now it will print numbers from 0 to 9
}

Notes:

  • Always check for the initialization, condition, and iteration expressions in a for loop.
  • A code review can help catch these kinds of errors before they lead to runtime issues.

Example 3: Recursion Without Base Case

Context: A recursive function intended to calculate factorial.

In this instance, a function is designed to compute the factorial of a number using recursion, but it lacks a base case, causing an infinite loop:

public int factorial(int n) {
    return n * factorial(n - 1);  // Missing base case
}

When calling factorial(5), the function keeps calling itself with decreasing values of n without ever stopping, eventually leading to a stack overflow. To prevent this, a base case must be added:

public int factorial(int n) {
    if (n == 0) return 1;  // Base case to stop recursion
    return n * factorial(n - 1);
}

Notes:

  • Always define a base case when using recursion to ensure that the function can terminate.
  • Consider using iterative methods for problems that are not inherently recursive to avoid potential stack overflow issues.