C# foreach statement
In this chapter you will learn:
- What is foreach statement
- How to create foreach loop statement
- Example for foreach loop
- Use break with a foreach
- Use foreach on a two-dimensional array
- Search an array using foreach
- Note for foreach loop
Description
The foreach
statement iterates over each element in an enumerable object.
Syntax
You can get an idea of the syntax of foreach
from the following code, if you assume that arrayOfInts
is an array of ints:
foreach (int temp in arrayOfInts)
{
Console.WriteLine(temp);
}
Here, foreach
steps through the array one element at a time. With each element,
it places the value of the
element in the int variable called temp and then performs an iteration of the loop.
Example 1
Example for foreach loop
using System;/*from w ww . j ava 2 s .co 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:
Example 2
Use break with a foreach
using System; //w w w .j a va2 s . c o 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.
Example 3
using System; /* w ww . java2 s . 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.
Example 4
Search an array using foreach
using System; /*from w w w . ja v a 2s . 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.
Note
You can't change the value of the item in the collection (temp in the preceding code), so code such as the following will not compile:
foreach (int temp in arrayOfInts)
{ /*from w ww . j a v a 2 s . co m*/
temp++;
Console.WriteLine(temp);
}
To iterate through the items in a collection and change their values, you will need to use a for loop instead.
Next chapter...
What you will learn in the next chapter:
- What is switch statement
- How to create switch statement
- Example for switch statement
- Example for switch statement based on string value
- Empty case