CSharp/C# Tutorial - C# for while foreach






while and do-while loops

while loops repeatedly execute a body of code while a bool expression is true.

The expression is tested before the body of the loop is executed.

For example:


int i = 0; 
while (i < 3) {
    Console.WriteLine (i); 
    i++; 
} 

do-while loops test the expression after the statement block has executed.

do-while loops ensure that the block is always executed at least once.

Here's the preceding example rewritten with a do-while loop:


int i = 0; 
do {
   Console.WriteLine (i);
   i++; 
} while (i < 3); 




for loops

for loops have clauses for initialization and iteration of a loop variable.

A for loop contains three clauses as follows:


for (initialization-clause; condition-clause; iteration-clause) 
    statement-or-statement-block 
    

Initialization clause is executed before the loop begins and is used to initialize one or more iteration variables.

Condition clause is a bool expression that, while true, will execute the body.

Iteration clause is executed after each iteration of the statement block and is used to update the iteration variable.

For example, the following prints the numbers 0 through 2:


for (int i = 0; i < 3; i++) 
    Console.WriteLine (i); 

An example.


using System; /*from  www .  j  a v  a 2s . co m*/
public class ScopeTest { 
   public static int Main() { 
      for (int i = 0; i < 10; i++) { 
         Console.WriteLine(i); 
      }  
      for (int i = 9; i >= 0; i -- ) 
      { 
         Console.WriteLine(i); 
      }   // i goes out of scope here. 
      return 0; 
   } 
} 

Any of the three parts of the for statement may be omitted.





foreach loops

The foreach statement iterates over each element in an enumerable object.

For example, both an array and a string are enumerable.

Here is an example of looping over the characters in a string, from the first character through to the last:


foreach (char c in "java2s.com"){ // c is the iteration variable 
   Console.WriteLine (c); 
}