Control Statements - Loops (2)
The for Loop
A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (<initializer list>; <boolean expression>; <iterator list>) { <statements> }.
At any point within the for block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.
The syntax of a for loop is:
for (initializer; condition; iterator){ statements}
#region For Loop
for (int i = 0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;
Console.Write("{0} \n", i);
}
#endregion
- First, the initial value of variable i is established. This step happens only once, regardless of how many times the loop repeats. You can think of this initialization as happening outside the looping process.
- To evaluate the condition (i < 20), the value of i is compared to 20.
- If i is less than or equal to 20, the condition evaluates to true, and the following actions occur.
- The if Condition evaluate the value of i (i == 10),as long as i not equal 10 it go to the next if,which evaluate the reminder of dividing i by 2 ,as long as the reminder = 0, The Console.WriteLine statement in the body of if will print i.
- The value of i is incremented by 1.
- The loop returns to the start of step 2 to evaluate the condition again.
- If i is greater than 20, the condition evaluates to false, and you exit the loop.
The ForEach Loop
- A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.
- The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
- The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.
- At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.
The syntax of a foreach loop is:
foreach (type iteration variable in list){
statements
}
class ForEachLoop
{
public static void Main()
{
#region foreach Loop
string[] names = { "Sam", "Joe", "Ali", "Ahmed" };
foreach (string person in names)
{
Console.WriteLine("{0} ", person);
}
#endregion
}
}
Post a Comment