Tutorial by Examples

While The most trivial loop type. Only drawback is there is no intrinsic clue to know where you are in the loop. /// loop while the condition satisfies while(condition) { /// do something } Do Similar to while, but the condition is evaluated at the end of the loop instead of the beginn...
Sometimes loop condition should be checked in the middle of the loop. The former is arguably more elegant than the latter: for (;;) { // precondition code that can change the value of should_end_loop expression if (should_end_loop) break; // do something } Alternati...
foreach will iterate over any object of a class that implements IEnumerable (take note that IEnumerable<T> inherits from it). Such objects include some built-in ones, but not limit to: List<T>, T[] (arrays of any type), Dictionary<TKey, TSource>, as well as interfaces like IQueryab...
int n = 0; while (n < 5) { Console.WriteLine(n); n++; } Output: 0 1 2 3 4 IEnumerators can be iterated with a while loop: // Call a custom method that takes a count, and returns an IEnumerator for a list // of strings with the names of theh largest city metro areas. ...
A For Loop is great for doing things a certain amount of time. It's like a While Loop but the increment is included with the condition. A For Loop is set up like this: for (Initialization; Condition; Increment) { // Code } Initialization - Makes a new local variable that can only be us...
It is similar to a while loop, except that it tests the condition at the end of the loop body. The Do - While loop executes the loop once irrespective of whether the condition is true or not. int[] numbers = new int[] { 6, 7, 8, 10 }; // Sum values from the array until we get a total that's ...
// Print the multiplication table up to 5s for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { int product = i * j; Console.WriteLine("{0} times {1} is {2}", i, j, product); } }
In addition to break, there is also the keyword continue. Instead of breaking completely the loop, it will simply skip the current iteration. It could be useful if you don't want some code to be executed if a particular value is set. Here's a simple example: for (int i = 1; i <= 10; i++) { ...

Page 1 of 1