For Loop Tester

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

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

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

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


   

/*
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");  
  }  
}

           
          


Declare loop control variable inside the for

/*
C#: The Complete Reference
by Herbert Schildt

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

using System;

public class ForVar {
public static void Main() {
int sum = 0;
int fact = 1;

// compute the factorial of the numbers through 5
for(int i = 1; i <= 5; i++) { sum += i; // i is known throughout the loop fact *= i; } // but, i is not known here. Console.WriteLine("Sum is " + sum); Console.WriteLine("Factorial is " + fact); } } [/csharp]

The body of a loop can be empty

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// The body of a loop can be empty.

using System;

public class Empty3 {
public static void Main() {
int i;
int sum = 0;

// sum the numbers through 5
for(i = 1; i <= 5; sum += i++) ; Console.WriteLine("Sum is " + sum); } } [/csharp]