Infinite Loops

From CompSciWiki
Revision as of 14:35, 10 February 2011 by Tandres (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

An infinite loop is any loop that either has no end condition or the end condition can never be satisfied.

   

{{{Body}}}

Causes

Infinite loops are caused by a loop's condition(s) not evaluating to false. This can be because the control variable may never change to end the loop as in Example 1. In Example 2 the condition for the loop will never be met because it will always be true. The if statement will never execute so the flag will never be set to true and so the loop will execute infinitely. Example 3 shows how changing the value of the control variable inside of the loop will cause it to repeat infinitely. Example 4 shows that an infinite loop is caused by an outer bound being given that an integer will not hold. Be wary of all these and always make sure your conditions for the end of a loop can be satisfied.

Examples

The Following code shows some common types of errors that will produce infinite loops. Infinite loops are a useful thing to be able to recognize. Being able to spot an infinite loop can help you debug your program.

Example 1:

int x = 1;
while( x > 0 )
{
     x = (x + 2) % 10 ;
}

Example 2:

boolean flag = false;
while(!flag) //always true
{
     if(flag)
          flag = true;
}

Example 3:

for(int i = 0; i < 20; i++) //counter reset to 0 every time
{
    i = 0;
}

Example 4:

//integers can't be as big as 9999999999999999, so 'i' will overflow to negative
for(int i = 0; i < 9999999999999999; i++)
{
     // Statements
}

Solutions

Infinite loops can be avoided by making sure it is possible to satisfy the end condition. Be careful to watch your conditions and bounds and you should be able to spot where and why your infinite loop is happening.