Compare foreach and for loop in CSharp

Description

The following code shows how to compare foreach and for loop.

Example


using System; /*from   www  .  ja  v  a 2  s.  c  om*/
 
public class MainClass {     
  public static void Main() { 
    int sum = 0; 
    int[] nums = new int[10]; 
 
    for(int i = 0; i < 10; i++)  
      nums[i] = i; 
 
    Console.WriteLine("use foreach to display and sum the values");
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
    } 
    Console.WriteLine("Summation: " + sum); 
  } 
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception