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:

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:

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 (==).

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:

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:

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:

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

7 thoughts on “The Infinite Loop in C

  1. I m confused in example 4. i copy and pasted and run the program(with error) and the result was same as written in example 4 i.e there is an infinite loop but i couldn’t understand why f could not be equal to 31.000000 i mean we are only incrementing +.1 so 2 will become 2.1 in first iteration and then 2.2 in 2nd and 2.3 in 3rd and 3 in 10th iteration and so on until 2 will become 31.000000. plz help me friends

Leave a Comment