foreach

In this chapter you will learn:

  1. How to use foreach loop
  2. Use break with a foreach
  3. Use foreach on a two-dimensional array
  4. Search an array using foreach

Get to know foreach loop

foreach loop is for the enumerable object. An array is an enumerable object.

The following code uses the foreach to print out the value for each element in an array.

The general form of foreach is shown here:

foreach(type var-name in collection) 
       statement;
using System;/*j ava  2 s.  c o  m*/

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        foreach (int i in intArray)
        {
            Console.WriteLine(i);
        }
    }
}

The output:

Use break with a foreach

using System; //jav  a  2  s .co  m
 
class MainClass { 
  public static void Main() { 
    int sum = 0; 
    int[] nums = new int[10]; 
 
    for(int i = 0; i < 10; i++)  
      nums[i] = i; 
 
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
      if(x == 4) 
         break; // stop the loop when 4 is obtained 
    } 
    Console.WriteLine("Summation of first 5 elements: " + sum); 
  } 
}

The code above generates the following result.

Use foreach on a two-dimensional array

using System; //from   j  a v a2s  .  co m
 
class MainClass { 
  public static void Main() { 
    int sum = 0; 
    int[,] nums = new int[3,5]; 
 
    for(int i = 0; i < 3; i++)  
      for(int j=0; j < 5; j++) 
        nums[i,j] = (i+1)*(j+1); 
 
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
    } 
    Console.WriteLine("Summation: " + sum); 
  } 
}

The code above generates the following result.

Search an array using foreach

using System; /*from   j  a  v  a2 s  .c  o m*/
 
class MainClass { 
  public static void Main() { 
    int[] nums = new int[10]; 
    int val; 
    bool found = false; 
 
    for(int i = 0; i < 10; i++)  
      nums[i] = i; 
 
    val = 5; 
 
    foreach(int x in nums) { 
      if(x == val) { 
        found = true; 
        break; 
      } 
    } 
 
    if(found)  
      Console.WriteLine("Value found!"); 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Get to know the syntax of switch statement
  2. Group case statements together
  3. Empty cases can fall through
Home » C# Tutorial » Statements
Comments
if Statement
while loop
do...while loop
for loop
foreach
switch
break
continue statement
goto statement
Xml Documentation