/* * C# Programmers Pocket Consultant * Author: Gregory S. MacBeth * Email: gmacbeth@comporium.net * Create Date: June 27, 2003 * Last Modified Date: */ using System; using System.Collections; namespace Client.Chapter_4___Program_Control { public class ForEaches { static void Main(string[] args) { ArrayList a = new ArrayList(10); foreach (int x in a) { Console.WriteLine(x); } } } }
Language Basics
Update two parameters in for loop
using System;
class CommaOp1
{
const int StartChar = 33;
const int EndChar = 125;
const int CharactersPerLine = 5;
static public void Main()
{
for (int i = StartChar, j = 1; i <= EndChar; i++, j++)
{
Console.Write("{0}={1} ", i, (char)i);
if (0 == (j % CharactersPerLine))
{
Console.WriteLine("");
}
}
}
}
[/csharp]
a for loop to display 1 to 5
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example4_11.cs illustrates the use of
a for loop to display 1 to 5
*/
public class Example4_11
{
public static void Main()
{
for (int counter = 1; counter <= 5; counter++) { System.Console.WriteLine("counter = " + counter); } } } [/csharp]
For with empty condition
/* Learning C# by Jesse Liberty Publisher: O'Reilly ISBN: 0596003765 */ using System; public class ForEmptyTester { public static void Main() { int counterVariable = 0; // initialization for ( ;; ) { Console.WriteLine( "counter: {0} ", counterVariable++); // increment if (counterVariable > 10) // test break; } } }
For without increase
/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
public class ForWithoutIncrTester
{
public static void Main()
{
for (int counter = 0; counter<10; ) // no increment { Console.WriteLine( "counter: {0} ", counter); // do more work here counter++; // increment counter } } } [/csharp]
For without init value
/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
public class ForWithoutTester
{
public static void Main()
{
int counter = 0;
// some work here
counter = 3;
// more work here
for ( ; counter<10; counter++) { Console.WriteLine( "counter: {0} ", counter); } } } [/csharp]
If inside a for
/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
public class ForIfTester
{
public static void Main()
{
for (int counter=0; counter<10; counter++)
{
Console.WriteLine(
"counter: {0} ", counter);
// if condition is met, break out.
if (counter == 5) {
Console.WriteLine("Breaking out of the loop");
break;
}
}
Console.WriteLine("For loop ended");
}
}
[/csharp]