Start learning free

LESSON 117 OF 347 · WHILE LOOPS & FOR LOOPS

Infinite While Loops in C#: Causes and Fixes

Lesson Read the full explanation

Loops bring great power but also great responsability. The biggest danger when using loops is writing an infinite loop.

An infinite loop is a loop that never terminates. For example, if we forget to increment i in our previous example:

int i = 1;
while(i < 5) {
	Console.WriteLine(i);
	// i++; => forgot this
}

This program will never terminate as i will always have value 1 and thus the condition i < 5 will always be satisfied.

The program would basically print 1 forever never exiting the while loop.


Pro Tip:

As programmers, we want to make sure we never write infinite loops as they make our program run forever and completely unusable.


Assignment
Follow the Coding Tutorial and practice with infinite while loops!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    C# · WHILE LOOPS & FOR LOOPS

    Infinite While Loops in C#, explained

    What an infinite loop is

    A while loop repeats its body for as long as its condition is true. An infinite loop is one whose condition never becomes false, so the program keeps repeating the body instead of moving on. The typical symptoms are a console that fills with the same output, or a program that seems frozen.

    Two mistakes cause almost every infinite while loop:

    • The loop variable is never updated, so the condition sees the same value on every pass.
    • The variable is updated, but in a way that never makes the condition false.

    Forgetting the update

    int i = 1;
    while (i < 5) {
        Console.WriteLine(i);
        // i++; was forgotten
    }
    

    Here i stays at 1, so i < 5 is true forever and the loop prints 1 over and over. Adding i++; inside the body fixes it: i grows to 5, the condition fails, and the loop ends.

    Updating the wrong way

    Counting up in a loop that is supposed to count down is the same bug in disguise. With while (i > 0) and i++, the value moves away from the stopping point on every pass.

    The exercise: the loop that skips past 0

    The lesson gives you a loop that should print the odd numbers from 15 down to 1 and then stop:

    int counter = 15;
    while (counter != 0) {
        Console.WriteLine(counter);
        counter -= 2;
    }
    

    The direction is right, because counter shrinks by 2 each time. The problem is the condition. Follow the values: 15, 13, 11, 9, 7, 5, 3, 1, and then -1. The counter starts odd and loses 2 each time, so it stays odd and never equals 0. It steps over 0 without landing on it. The condition counter != 0 stays true, and the loop keeps printing -1, -3, -5 and so on.

    The fix

    Ask the question the loop really needs: "is there still a positive number to print?" That is a range check, not an exact match:

    int counter = 15;
    while (counter > 0) {
        Console.WriteLine(counter);
        counter -= 2;
    }
    

    After the pass that prints 1, the counter becomes -1, -1 > 0 is false, and the loop ends. The output is 15, 13, 11, 9, 7, 5, 3, 1, each on its own line.

    Why != is a risky stopping condition

    Checking for an exact value only works when the loop is guaranteed to land on it. If the step is 1 and you start below the target, that holds. If the step is 2, 3 or anything larger, or if the starting value has the wrong parity, the counter can jump over the target. A comparison such as >, <, >= or <= still stops the loop in that case, because the value ends up on the wrong side of the limit.

    A C# detail: int overflow

    An int in C# has a fixed range, and by default arithmetic that goes past the end wraps around silently instead of raising an error. So a loop like while (counter != 0) that keeps counting up is not strictly endless: the value eventually passes int.MaxValue, wraps to a large negative number and climbs back towards 0. With a start of 15, that takes more than four billion passes. In practice the program prints for a very long time, which looks the same as an infinite loop to you.

    How to find and avoid infinite loops

    • Trace the first few passes by hand and write down the loop variable after each one. Ask whether it moves towards the point where the condition becomes false.
    • Look at the last few values before the intended stop, not just the first ones. That is where a skipped-over target shows up.
    • Prefer range conditions when the step is bigger than 1.
    • If a program seems stuck while testing, stop it with Ctrl+C in a terminal and check the loop first.

    Key takeaways

    • A while loop must change something that its condition depends on.
    • The change must move towards making the condition false.
    • Exact checks like != 0 break when the counter can jump over the value; > 0 does not.
    • Integer overflow in C# wraps silently, so a runaway counter can look endless without being so.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free