C# | Using foreach loop in arrays

Last Updated : 23 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

C# language provides several techniques to read a collection of items. One of which is foreach loop. The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or the collections in the program. Because the foreach loop can only iterate any array or any collections which previously declared. We cannot print a sequence of number or character using foreach loop like for loop, see below:

for(i = 0; i <= 10; i++)
// we cannot use foreach loop in this way to print 1 to 10
// to print 1 to 10 using foreach loop we need to declare 
// an array or a collection of size 10 and a variable that 
// can hold 1 to 10 integer

Syntax of foreach Loop:

foreach (Data_Type variable_name in Collection_or_array_Object_name)
 {
   //body of foreach loop
 }
// here "in" is a keyword

Here Data_Type is a data-type of the variable and variable_name is the variable which will iterate the loop condition (for example, for(int i=0; i<10;i++), here i is equivalent to variable_name). The in keyword used in foreach loop to iterate over the iterable-item(which is here the array or the collections). The in keyword selects an item from the iterable-item or the array or collection on each iteration and store it in the variable(here variable_name). Example 1: Below is the implementation of the "for" and "foreach" loop using arrays 

CSharp
// C# program to show the use of 
// "for" loop and "foreach" loop 
using System; 


class GFG { 

    // Main Method 
    public static void Main() 
    { 

        // initialize the array 
        char[] arr = {'G', 'e', 'e', 'k', 's', 
                        'f', 'o', 'r', 'G', 'e', 
                                'e', 'k', 's'}; 
        

        Console.Write("Array printing using for loop = "); 

        // simple "for" loop 
        for (int i = 0; i < arr.Length; i++) 
        { 
            Console.Write(arr[i]); 
        } 

        Console.WriteLine(); 

        Console.Write("Array printing using foreach loop = "); 

        // "foreach" loop 
        // "ch" is the variable 
        // of type "char" 
        // "arr" is the array 
        // which is going to iterates 
        foreach(char ch in arr) 
        { 
            Console.Write(ch); 
        } 
    } 
} 

Output
Array printing using for loop = GeeksforGeeks
Array printing using foreach loop = GeeksforGeeks

Time Complexity: O(N), here N is number of characters in array(arr).
Auxiliary Space: O(1), since no extra space used.

Example 2: Traversing of an array using "foreach" loop 

CSharp
// C# program to traverse an 
// array using "foreach" loop 
using System; 

class GFG { 

    // Main Method 
    public static void Main() 
    { 
        char[] s = {'1', '4', '3', '1', 
                    '4', '3', '1', '4', 
                                '3'}; 
        int m = 0, n = 0, p = 0; 

        // here variable "g" is "char" type 
        //'g' iterates through array "s" 
        // and search for the numbers 
        // according to below conditions 
        foreach(char g in s) 
        { 
            if (g == '1') 
                m++; 
            else if (g == '4') 
                n++; 
            else
                p++; 
        } 
        Console.WriteLine("Number of '1' = {0}", m); 
        Console.WriteLine("Number of '4' = {0}", n); 
        Console.WriteLine("Number of '3' = {0}", p); 
    } 
} 

Output
Number of '1' = 3
Number of '4' = 3
Number of '3' = 3

Note: At anywhere within the scope of foreach loop, we can break out of the loop by using the break keyword, and can also go to the next iteration in the loop by using the continue keyword. Example: Using "continue" and "break" keyword in foreach loop 

CSharp
// C# program to demonstrate the use 
// of continue and break statement 
// in foreach loop 
using System; 

class GFG { 

    // Main Method 
    public static void Main() 
    { 

        // initialize the array 
        int[] arr = {1, 3, 7, 5, 8, 
                    6, 4, 2, 12}; 

        Console.WriteLine("Using continue:"); 
        
        foreach(int i in arr) 
        { 
            if (i == 7) 
                continue; 
            // here the control skips the next 
            // line if the "i" value is 7 

            // this line executed because 
            // of the "if" condition 
            Console.Write(i + " "); 

        } 

        Console.WriteLine(); 
        Console.WriteLine("Using break:"); 
        
        foreach(int i in arr) 
        { 
            
            if(i == 7) 
            // here if i become 7 then it will 
            // skip all the further looping 
            // statements 
                break; 
            Console.Write(i +" "); 
        } 
    } 
} 

Output
Using continue:
1 3 5 8 6 4 2 12 
Using break:
1 3 

Time Complexity: O(N), here N is number of characters in array(arr).
Auxiliary Space: O(1), since no extra space used.


Next Article

Similar Reads