Nov 30 2011, 05:17 PM
here's a more proper write up about the different loops.
For loop:
the for loop is used to execute code so long as the iteration condition is true, i.e. i < 10
infinite for loop has no condition.:
the structure of a for loop
you can have multiple variables aswel
while loop:
a while loop doesn't have a counter variable, it executes so long as the condition is true.
a while loop executes the condition first and tests then executes code.
do-while loop:
this is the same as a while loop except code execution happens first, then condition execution.
other than that the do-while and while are the same
for-each is used for iterating through an iteratable collection.
as it iterates through the collection the holder variable is filled with whatever is in the current location in the collection and can be used as a direct reference to the object (not a copy) so changing the holder changes the object in the collection.
the important thing to remember when using loops is to always have a way out, infinite loops are not your friend. in a for loop make sure your condition will eventually return false. in your while/do-while loop make sure your condition can either return false or your code has a breakout somewhere.
For loop:
the for loop is used to execute code so long as the iteration condition is true, i.e. i < 10
infinite for loop has no condition.:
Code:
for(;;) { }
the structure of a for loop
Code:
for(counter initialization; condition; counter change) { code }
you can have multiple variables aswel
Code:
for(int i = 0, int k = 100; i <= 50 && k >= 50; i++, k--) { }
while loop:
a while loop doesn't have a counter variable, it executes so long as the condition is true.
Code:
while(condition) { code }
do-while loop:
this is the same as a while loop except code execution happens first, then condition execution.
Code:
do {
code will always execute atleast once
} while (condition)
for-each is used for iterating through an iteratable collection.
Code:
foreach(holderVariable in iterableObject) { code }
the important thing to remember when using loops is to always have a way out, infinite loops are not your friend. in a for loop make sure your condition will eventually return false. in your while/do-while loop make sure your condition can either return false or your code has a breakout somewhere.