Open In App

C# | foreach Loop

Prerequisite: Loops in C#

Looping in a programming language is a way to execute a statement or a set of statements multiple numbers of times depending on the result of a condition to be evaluated. The resulting condition should be true to execute statements within loops. The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.



Syntax:

foreach(data_type var_name in collection_variable)
{
     // statements to be executed
}

Flowchart:



Example 1:




// C# program to illustrate the
// use of foreach loop
using System;
  
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        Console.WriteLine("Print array:");
  
        // creating an array
        int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };
  
        // foreach loop begin
        // it will run till the
        // last element of the array
        foreach(int items in a_array)
        {
            Console.WriteLine(items);
        }
    }
}

Output:
Print array:
1
2
3
4
5
6
7

Explanation: foreach loop in above program is equivalent to:

for(int items = 0; items < a_array.Length; items++)
{
    Console.WriteLine(a_array[items]);
}

Example 2:




// C# program to illustrate 
// foreach loop 
using System;
  
class For_Each     
{
      
    // Main Method
    public static void Main(String[] arg) 
    
        
            int[] marks = { 125, 132, 95, 116, 110 }; 
              
            int highest_marks = maximum(marks); 
              
            Console.WriteLine("The highest score is " + highest_marks); 
        
    
      
    // method to find maximum
    public static int maximum(int[] numbers) 
    
        int maxSoFar = numbers[0]; 
          
        // for each loop 
        foreach (int num in numbers) 
        
            if (num > maxSoFar) 
            
                maxSoFar = num; 
            
        
    return maxSoFar; 
    

Output:
The highest score is 132

Limitations of foreach loop:

  1. Foreach loops are not appropriate when you want to modify the array:
    foreach(int num in marks) 
    {
        // only changes num not
        // the array element
        num = num * 2; 
    }
    
  2. Foreach loops do not keep track of index. So we can not obtain array index using ForEach loop
    foreach (int num in numbers) 
    { 
        if (num == target) 
        {
            return ???;   // do not know the index of num
        }
    }
    
  3. Foreach only iterates forward over the array in single steps
    // cannot be converted to a foreach loop
    for (int i = numbers.Length - 1; i > 0; i--) 
    {
         Console.WriteLine(numbers[i]);
    }
    

Difference between for loop and foreach loop:


Article Tags :
C#