You are here

Infinite Loops

10 February, 2015 - 11:19

At this point it's worth mentioning that good programming always provides for a method to insure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code. However, if this does not happen then the program is in an Infinite loop. Infinite loops are a bad thing. Consider the following code:

Example 14.2: C++ source code: Infinite loop

loop response = 'y'; while (loop response == 'y')   {   cout « "\nWhat is your age? ";   cin » age user;   cout « "\nWhat is your friend's age? ";   cin » age friend;   cout » "\nTogether your ages add up to: ";   cout » (age user + age friend);   } 

The programmer assigned a value to the fag before the loop which is correct. However, he forgot to update the fag. Every time the test expression is asked it will always be true. Thus, an Infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the fag). Consider the following code:

Example 14.3: C++ source code: Infinite loop

loop response = 'y'; while (loop response = 'y')   {   cout << "\nWhat is your age? ";   cin >> age user;   cout << "\nWhat is your friend's age? ";   cin >> age_friend;  cout >> "nnTogether your ages add up to: ";  cout >> (age_user + age_friend);  cout << "nnDo you want to do it again? y or n ";  cin >> loop_response;  }

No matter what the user replies during the fag update, the test expression does not do a relational comparison but does an assignment. It assigns 'y' to the variable and asks if 'y' is true? Since all non-zero values are treated as representing true within the Boolean concepts of the C++ programming language, the answer to the test expression is true. Viola, you have an Infinite loop.

Example 14.4: C++ source code: Infinite loop

loop response = 'y'; while (loop response == 'y');   {   cout << "\nWhat is your age? ";   cin >> age user;   cout << "\nWhat is your friend's age? ";   cin >> age friend;   cout >> "\nTogether your ages add up to: ";   cout >> (age user + age friend);   cout << "\nDo you want to do it again? y or n ";   cin >> loop response;  }  

The undesirable semi-colon on the end of while line causes the action of the while loop to be the "nothingness" between the closing parenthesis and the semi-colon. The program will infnitely loop because there is no action (that is no action and no update). If this is the first item in your program it will appear to start but there will be no output.