Foreach Loop

Using Foreach Loop

The foreach loop is a type of loop for arrays. How long the loop will rotate will be automatically calculated by the program depending on the number of elements in the array. For each element of the array we specified in the definition part of the loop, the loop will return once. And at each step, the next array element will be taken into the specified variable.

foreach ( variableType variableName in arrayName )

{

Operations for each element of the array

}

 

Example :

foreach ( int a in numbers )

{

Label1.text += a.toString() + “ “;

}

In the above example, at each step of the loop, the next element of the number array is taken into variable a. Thanks to this variable a, we get the current element of the array and we can do whatever we want.

The type of the specified variable and the type of the array must match. Otherwise, an error occurs.

Example: Let's find the sum of all the elements of a numeric array.

int[] numbers = {5,12,6,4,14,56,2,125};

int total = 0 ;

foreach(int i in numbers)

{

total += i ;

}

label1.Text = total.ToString();

 

foreach loop tutorials, foreach examples, foreach arrays, printing array with foreach loop, how to use foreach loop

EXERCISES

Assigning random values to array items

With foreach loop

label1.Text = "";
Random random = new Random();
int[] numbers = new int[10];
int  indexNo = 0;
 
foreach (int i in numbers)
{
   numbers[indexNo] = random.Next(0, 1000);
   indexNo++;
}
 
foreach (int i in numbers)
{
   label1.Text += i.ToString() + "\n";
}
 
with for loop
label1.Text = "";
Random random = new Random();
int[] numbers = new int[10];
 
for (int i = 0; i <= 9; i++)
{
   numbers[i] = random.Next(0, 1000);
}
 
foreach (int i in numbers)
{
    label1.Text += i.ToString() + "\n";
}

 



COMMENTS




Read 566 times.

Online Users: 783



c-sharp-foreach-loop