![]() |
|
Looping structures used in C#, Free online C# Programming Tutorial... |
| Lessons | C# Loops |
|
The syntax of while, do-while, and for loops is similar to C++ and Java. Basic syntax of C# loops is given as under: while Loop: while (booleanExpression) //repeating C# statement(s) do-while Loop: do //repeating C# statement(s) while (booleanExpression); for Loop: for (initialization; Boolean expression; update control variable) //repearing C# statement(s) You need to remember that unlike C++ the loop control expression must be of Boolean type. foreach Loop: The foreach loop was not available in C++. It is used to iterate through the values contained in any object that implements the IEnumerable interface. It has the following syntax: foreach (variable1 in variable2) //repeating C# statement(s) When a 'foreach' loop runs, the given variable1 is set in turn to each value exposed by the object named by variable2. Here is an example: int[] a = new int[]{1,2,3}; foreach (int b in a) System.Console.WriteLine(b); The above code outputs: 1 2 3
Next >>> Lesson No. 8: C# switch
|