View Single Post
  #3 (permalink)  
Old June 11th, 2012, 02:21 PM
drpepper drpepper is offline
Authorized User
Points: 267, Level: 5
Points: 267, Level: 5 Points: 267, Level: 5 Points: 267, Level: 5
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: May 2012
Posts: 66
Thanks: 0
Thanked 4 Times in 4 Posts
Default

AnTiDoD,

I am making a big leap here. I think the code which produces an endless loop either uses double x = 2.0; or x += 2.0;. The code would look like this:
Code:
for (double x =2.0; x!= 1.0; x+= 0.2)
  cout << x;
or this
Code:
for (double x = 0.0; x!= 1.0; x+= 2.0)
  cout << x;
Something that works for me to answer questions like yours is to play computer on paper, writing down the inputs, outputs, and values of all variables for a complete run of the program. Where different values are used to test the program, I test each value separately.

so... Let's do an abbreviated form of play computer
Code:
for (double x = 2.0; x!= 1.0; x+= 0.2)
  cout << x;
x is declared and initialized to the value of 2.0
x is not equal to 1.0, and never will be
the loop is infinite
Code:
for (double x = 0.0; x!= 1.0; x+= 2.0)
  cout << x;
x is declared and initialized to the value 0.0
x is not equal to 1.0; so the value of x is output
x is incremented by 2.0, making the value 2.0
x is not equal to 1.0, and never will be after this point in time
the loop is infinite

The code you provided works like this.
Code:
for (double x = 0.0; x!= 1.0; x+= 0.2)
  cout << x;
x is declared and initialized to the value of 0.0
x is not equal to 1.0; so the value of x is output
x is incremented by 0.2, making the value 0.2
x is not equal to 1.0; so the value of x is output
x is incremented again repeatedly until the value of x is equal to 1.0
the loop is terminated and the flow passes to the next line of executable code

The intended syntax to illustrate an endless loop could not use x! =2;. Substituting the condition with x != 2.0 produces the same result with the exception that the loop is not terminated until the value of x is 2.0

I hope this is helpful.

drpepper