For without init value

image_pdfimage_print

/*
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

image_pdfimage_print

/*
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]

For Loop Tester

image_pdfimage_print

/*
Learning C#
by Jesse Liberty

Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
public class ForTester
{

public static void Main()
{
for (int counter=0; counter<10; counter++) { Console.WriteLine( "counter: {0} ", counter); } } } [/csharp]

Compute the sum and product of the numbers from 1 to 10.

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Compute the sum and product of the numbers from 1 to 10.

using System;

public class ProdSum {
static void Main() {
int prod;
int sum;
int i;

sum = 0;
prod = 1;

for(i=1; i <= 10; i++) { sum = sum + i; prod = prod * i; } Console.WriteLine("Sum is " + sum); Console.WriteLine("Product is " + prod); } } [/csharp]

Demonstrate the for loop

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate the for loop.

using System;

public class ForDemo {
public static void Main() {
int count;

for(count = 0; count < 5; count = count+1) Console.WriteLine("This is count: " + count); Console.WriteLine("Done!"); } } [/csharp]

Use continue

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use continue.

using System;

public class ContDemo {
public static void Main() {
// print even numbers between 0 and 100
for(int i = 0; i <= 100; i++) { if((i%2) != 0) continue; // iterate Console.WriteLine(i); } } } [/csharp]

Using break to exit a loop

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using break to exit a loop.   
 
using System; 
 
public class BreakDemo {  
  public static void Main() {  
 
    // use break to exit this loop 
    for(int i=-10; i <= 10; i++) {  
      if(i > 0) break; // terminate loop when i is positive 
      Console.Write(i + " ");  
    }  
    Console.WriteLine("Done");  
  }  
}