The foreach loop in C#
Loops in C#:
Introduction :
There are multiple ways to writing the loops in
C#
the most basics loops in any programming languages arefor
andwhile
loop. InC#
we have another type of advance loop that is theforeach
loop. We will see thesyntax
and execution of theforeach
loop below.Before we talk about the advanced
foreach
loop let me just give a brief explanation of the other looping condition.
Types of Loops :
Loops | When to use the Loop |
for | We can use this loop whenever we know the starting and ending conditions. |
while | We can use this loop whenever we don't know the starting condition but we know the end condition. |
do-while | We can use this loop whenever we want to execute the loop at least one time before it checks the condition. |
foreach | We can use this advanced for loop in concepts like Array and other data structure concepts where we don't want to use the index number to access the elements or Some of the data structure they don't have the index concept. |
foreach
loop :
foreach
is advancedfor
loop which can be used to access the element of the collection without using indexes.
Syntax :
foreach(data_type var_name in collection_var) {
//statements
}
Understanding the foreach
loop :
using System;
// Topic: foreach
class MainClass {
public static void Main (string[] args)
{
int[] num = {1,2,3,4,5};
Console.WriteLine("Using the for loop");
//for loop
for(int i=0;i<num.Length;i++)
{
Console.WriteLine(num[i]);
}
Console.WriteLine("Using the foreach loop");
//foreach loop
foreach(int a in num)
{
Console.WriteLine(a);
}
}
}
Output :
Using the for loop
1
2
3
4
5
Using the foreach loop
1
2
3
4
5
Explanation :
for
loop :
- In the above code, you can see using the
for
loop we need to access the elements using the index value. Here using thefor
loop we need to keep the index values in check that is if the index values are in the range of the given collection/array length or else this will lead to theSystem.IndexOutOfRangeException
. And also, we need to increment/decrement the index value as per our required outputs.
foreach
loop :
- Like
for
loop this doesn't use any kind of index to retrieve elements from the array. This advancedforeach
loop will take the array and retrieve the elements one by one until the array will not have any elements left. This happens because if the array has elements then theforeach
loop returnstrue
else it will returnfalse
and stop the execution.