Using for Loops


Using for Loops

for loops are written to execute a loop for a fixed number of times.

for loops are very powerful constructs. They are divided into three parts . The first part is the initialization part. In the initialization part you can declare multiple variables that can be used as part of the loop. The second part of the for loop is the test part. The loop continues to execute while the test part is equal to true. The third part of the for loop is the execution part. At the end of each loop the code will execute the third portion of the for statement. When wanting to execute a series of statements in a loop a certain number of times a variable that serves as the counter is initialized in the first part of the statement; the second part of the statement tests to see if the counter variable is below a certain value; and the third part of the statement increases the counter by one in each iteration.

To write a for loop that executes for a specified number of times:

  1. Type for .

  2. Type an open parenthesis ( .

  3. Type int count=0 , where count is the name of the variable that will be used for the counter.

  4. Type a semicolon ; .

  5. Type count < 10 , where 10 is the number of times that you would like to loop. You can optionally use another variable for the comparison.

  6. Type another semicolon ;.

  7. Type count++ .

  8. Type a close parenthesis ) .

  9. Type an open curly bracket { .

  10. Type the statements that you wish to execute inside the loop.

  11. Type a close curly bracket } ( Figure 3.39 ).

    Figure 3.39 Assuming that items is an ArrayList, this code enumerates through all the items and calculates the total amount of the order.
     double total=0;  for (int i=0; i < items.Count; i++)   {  PurchasedItem item = (PurchasedItem)items[i];    total += item.Price * item.Quantity;  }  

graphics/tick.gif Tip

  • The for statement is very flexible. You can declare several variables in the first portion of the for statement, you can test that multiple criteria are met before continuing the loop, and you can even execute multiple statements in the execution part of the for ( Figure 3.40 ).

    Figure 3.40 Don't write code like that. It's here to show you how flexible for statements are.
     //extremely confusing for loop int m; for (  int count = 1, total = 500;   count < 10 && total > 200;   count++,total--,m = count * 100)  {    //do something interesting here    //I have no idea what } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net