Menu
Coddy logo textTech

Infinite Loop

Part of the Fundamentals section of Coddy's C# journey — lesson 47 of 69.

An infinite loop is a loop that never stops because its condition always evaluates to true. These loops can occur with any loop type (for, while, do-while), but they are most commonly associated with while and do-while loops because their conditions are explicitly stated.

Here's an example of an infinite while loop:

while (true) {
    Console.WriteLine("This will print forever!");
}

In this case, the condition is simply true, which always evaluates to true. Thus, the loop will run indefinitely, printing the message over and over again.

Another way to create an infinite loop is by omitting the condition in a for loop:

for (;;) {
    Console.WriteLine("This also prints forever!");
}

Here, the initialization, condition, and update parts of the for loop are all omitted. This creates a loop that runs forever.

Infinite loops can also occur unintentionally, such as when the loop's condition is always true due to a logic error:

int i = 0;
while (i < 10) {
    Console.WriteLine("i is: " + i);
    // Missing i++ to increment i
}

In this example, the variable i is never incremented, so the condition i < 10 is always true. This creates an infinite loop that will keep printing "i is: 0" indefinitely.

Infinite loops can be useful in some cases, such as in server programs that need to keep running until manually stopped. However, they can also cause programs to freeze or crash if not handled properly.

Cheat sheet

An infinite loop is a loop that never stops because its condition always evaluates to true.

Intentional infinite while loop:

while (true) {
    Console.WriteLine("This will print forever!");
}

Infinite for loop with omitted parts:

for (;;) {
    Console.WriteLine("This also prints forever!");
}

Unintentional infinite loop (missing increment):

int i = 0;
while (i < 10) {
    Console.WriteLine("i is: " + i);
    // Missing i++ to increment i
}

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals