Friday, April 4, 2008

C#. No4 - Control Statements - Loops

/resource from http://www.csharp-station.com/

The while Loop

The While Loop: WhileLoop.cs

using System;
class WhileLoop
{
public static void Main()
{
int myInt = 0;

while (myInt <>

The do Loop

The Do Loop: DoLoop.cs
using System;
class DoLoop
{
public static void Main()
{
string myChoice;

do

{
// Print A Menu
Console.WriteLine("My Address Book\n");

Console.WriteLine("A - Add New Address");
Console.WriteLine("D - Delete Address");
Console.WriteLine("M - Modify Address");
Console.WriteLine("V - View Addresses");
Console.WriteLine("Q - Quit\n");

Console.WriteLine("Choice (A,D,M,V,or Q): ");

// Retrieve the user's choice
myChoice = Console.ReadLine();

// Make a decision based on the user's choice
switch(myChoice)
{
case "A":
case "a":
Console.WriteLine("You wish to add an address.");
break;
case "D":
case "d":
Console.WriteLine("You wish to delete an address.");
break;
case "M":
case "m":
Console.WriteLine("You wish to modify an address.");
break;
case "V":
case "v":
Console.WriteLine("You wish to view the address list.");
break;
case "Q":
case "q":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("{0} is not a valid choice", myChoice);
break;
}

// Pause to allow the user to see the results
Console.Write("press Enter key to continue...");
Console.ReadLine();
Console.WriteLine();
}
while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
}
}

The for Loop

The For Loop: ForLoop.cs
using System;
class ForLoop
{
public static void Main()
{
for (int i=0; i <> if (i == 10)
break;

if (i % 2 == 0)
continue;

Console.Write("{0} ", i);
}
Console.WriteLine();
}
}

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.Collections namespace. The syntax of a foreach loop is foreach ( in ) { }. The type is the type of item contained in the list. For example, if the type of the list was int[] then the type would be int.

The item name is an identifier that you choose, which could be anything but should be meaningful. For example, if the list contained an array of people's ages, then a meaningful name for item name would be age.

The in keyword is required.

The ForEach Loop: ForEachLoop.cs

using System;
class ForEachLoop
{
public static void Main()
{
string[] names = {"Cheryl", "Joe", "Matt", "Robert"};

foreach
(string person in names)
{
Console.WriteLine("{0} ", person);
}
}
}

0 comments: