-C#- Loops - Printable Version +- (wL) Forums (https://war-lords.net/forum) +-- Forum: Resources (https://war-lords.net/forum/forum-31.html) +--- Forum: Programming (https://war-lords.net/forum/forum-33.html) +--- Thread: -C#- Loops (/thread-5186.html) |
-C#- Loops - MindHACKer - Nov 29 2011 Now to Repeat a single line of Code, ore a whole block there are 3 types of Loops: 1st: For 2nd: While 3rd: Do_While [glow=green,2,300]Basic Code Sample on (FOR):[/glow] -How to combine 10 Numbers with only 7 lines of Code- *Console App* Code: using System; [glow=green,2,300]Basic Code Sample on (While):[/glow] -I'll now write the same previous app but using "While"- *Console App* Code: using System; [glow=green,2,300]Basic Code Sample on (Do_While):[/glow] -I'll now write the same previous app but using "Do_While"- *Console App* Code: using System; NOTE: All do the same Function which is to Repeat. RE: -C#- Loops - Helices - Nov 29 2011 Well done! I'm currently researching more into C# and noticed there is one more loop style - the For-Each loop. Found in the System.Collections namespace, it is used to iterate through items in a list (array). This is a great implementation which allows easy processing or listing like attributes in said array. Counter and algorithms can be set in place if certain elements need to be ignored! One can also break from the loop at any time. Off the MSDN: Code: class ForEachTest RE: -C#- Loops - MindHACKer - Nov 29 2011 Well done! I'm going to post something about Arrays soon. RE: -C#- Loops - Leaky - Nov 30 2011 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 } do-while loop: this is the same as a while loop except code execution happens first, then condition execution. Code: do { 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. RE: -C#- Loops - MindHACKer - Nov 30 2011 Great work! |