Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
#4
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.:
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 }
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.
Code:
do {
code will always execute atleast once
} while (condition)
other than that the do-while and while are the same


for-each is used for iterating through an iteratable collection.
Code:
foreach(holderVariable in iterableObject) { code }
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.

Messages In This Thread
-C#- Loops - by MindHACKer - Nov 29 2011, 01:10 PM
RE: -C#- Loops - by Helices - Nov 29 2011, 06:07 PM
RE: -C#- Loops - by MindHACKer - Nov 29 2011, 06:10 PM
RE: -C#- Loops - by Leaky - Nov 30 2011, 05:17 PM
RE: -C#- Loops - by MindHACKer - Nov 30 2011, 05:26 PM

Users browsing this thread: 1 Guest(s)