The Infinite Loop in C

A loop that repeats indefinitely and never terminates is called an Infinite loop.

Loops that go on executing forever and never terminates because of lack of an exit condition are called infinite loops. Sometimes we create these loops by mistake, while sometimes we deliberately create them in our program. Let’s take some examples and see what kind of mistakes can lead to infinite loop.

Example 1:

int i;

for(i = 0; i < 100; i--)
{
    printf("%d\n", i);
}

This loop is an infinite loop. Here is why ? According to condition given, the loop will execute until (i < 100). Initially, the value of i is 0 and after each iteration, its value is decremented in the update expression (i--), so the value of i will never be greater than 100. Hence the condition (i < 100) will always be true. To make it finite we should use i++ instead of i--.

Example 2:

int i = 1

while(i<10)
{
    printf("%d\n", i); 
}

Here we are not updating the value of i. So after each iteration value of i remains same. As a result, the condition (i<10) will always be true. For the loop to work correctly add i++;, just after the printf() statement.

Always Remember, it is easy to forget update expression in while and do while loop, than in for loop.

Example 3:

Another common mistake that lead to infinite loop is to use assignment operator (=) where equality operator is needed (==).

int i = 1;

while(n=10)
{
    // some logic here
}

What we actually wanted is that loop should execute until n is equal to 10. The value of the whole expression (n=10) is 10, since a non-zero value is considered true, the condition is always true and the loop will go on to execute indefinitely. To fix the problem use (n==10) instead of (n=10).

Example 4:

float f = 2;

while(f != 31.0)
{
    printf("%f\n", f);
    f += 0.1;
}

This loop is infinite because computers represent floating point numbers as approximate numbers, so 3.0 may be stored as 2.999999 or 3.00001. So the condition (f != 31.0) never becomes false. To fix this problem write the condition as f <= 31.0.

Example 5:

int i = 0;

while(i<=5);
printf("%d\n", i);

This loop will produce no output and will go on executing indefinitely. Take a closer look and notice the semicolon(;) at the end of while condition. We know semicolon(;) after the condition is a null statement. So the loop is treated as following:

int i = 0;

while(i<=5)
{
    ; // a null statement
}

printf("%d\n", i);

As you can see there is no update expression inside the while loop, that's why it will go on executing indefinitely.