Tuesday, February 14, 2012

4.4.9. Iterating with "foreach"

There is an alternative loop command, similar to "for", but more adequate to iterate through certain data structures, such as the arrays (and other we will see).

It is used with the format "foreach (variable in SetOfValues)":

/*---------------------------*/
/*  C# Example #45:          */
/*  example45.cs             */
/*                           */
/*  Example of "foreach"     */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example45
{

  public static void Main()
  {
    int[] daysInMonth = {31, 28, 31};
    foreach(int days in daysInMonth)
    {
      Console.WriteLine("Days in the month: {0}", days);  
    }
   
    string[] names = {"Albert", "Andrew", "Anthony"};
    foreach(string name in names)
    {
      Console.Write(" {0}", name);  
    }
    Console.WriteLine();
   
    string greeting = "Hello";
    foreach(char letra in greeting)
    {
      Console.Write("{0}-", letra);  
    }
    Console.WriteLine();
   
  }
}

No comments:

Post a Comment