The foreach loop is generally used for iteration through array elements in different programming languages.
Example 1: (Basic Foreach Loop)
This is the basic example of the foreach statement.
1 2 3 4 5 6 7 8 9 10 11 | static void Main(string[] args) { var numbers = new List<int>() { 10, 15, 20, 30, 40, 55, 70, 100 }; foreach(int number in numbers) { Console.WriteLine(number); } Console.ReadKey(); } |
Output:
Example 2: (Foreach with continue)
If the continue statement is used within the loop body, it immediately goes to the next iteration skipping the remaining code of the current iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | static void Main(string[] args) { var numbers = new List<int>() { 10, 15, 20, 30, 40, 55, 70, 100 }; foreach(int number in numbers) { if(number==20 || number==30) { continue; } Console.WriteLine(number); } Console.ReadKey(); } |
Output:
Example 2: (Foreach with break)
If the break statement is used within the loop body, it stops the loop iterations and goes immediately after the loop body.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | static void Main(string[] args) { var numbers = new List<int>() { 10, 15, 20, 30, 40, 55, 30, 17 }; foreach(int number in numbers) { if(number>50) { break; } Console.WriteLine(number); } Console.ReadKey(); } |
Output: