Thread: C Foxtrot Comic
View Single Post
Old 10-10-2003, 03:04 PM   #32 (permalink)
charliex
Junkie
 
Location: North Hollywood
hrdwareguy: nope, you are missing the key point,
2 to 501 is inclusive which equals 500 steps.

example

say it was i=1 to i<=5 instead of 500 so
int i ; while (i<=5){ i++ };

program starts :
i = 1

:loop starts

is i less than or equal to 5 ? i=1, so yes, continue.

i is incremented to 2
"message is printed' (1rst time)

go back to top of loop

is i less than or equal to 5 ? i=2 so yes, continue.

i is incremented , is now 3
"message is printed' ( 2nd time)

go back to top of loop

is i less than or equal to 5 ? i=3 so yes, continue.

i is incremented , is now 4
"message is printed' (3rd time)

go back to top of loop

is i less than or equal to 5 ? i=4 so yes, continue.

i is incremented , is now 5
"message is printed' (4th time)

go back to top of loop

is i less than or equal to 5 ? i=5 so yes, continue. (not the key part here is less than *or* equal to 5 = 5 so its true, so it meets the condition.

i is incremented , is now 6
"message is printed' (5th time)

go to start of loop

is i less than or equal to 5 ? i is now 6, so stop the loop since 6 <= 5 is false (0)

5 messages were printed.

This is quite a common mistake made for junior or new programmers, its similar to people using the 5th element on an array defined as say int[5] and then using i = array[5]; which is of course the 6th element.

Last edited by charliex; 10-10-2003 at 03:12 PM..
charliex is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62