foreach loop in C#

foreach is simplified version of for loop. foreach loop used with collections such as an array.

syntax:

foreach( datatatype variable_name in collection_type_variable)
{
}

Like for loop , there is no initialization, condition and increment or decrement operation in foreach loop.

In foreach loop the variable of loop will be same as type of values under the array

For Example

string[] student=new string[] {"Peter", "John", "Lisa"};

To use the string array in for each loop for iterations , The varaible of the loop is also a string type.

foreach(string name in student)
{
}

C# Program to print the student names in an array using foreach loop

below program prints the student name on console.

C# code

class Program
    {
        static void Main(string[] args)
        {
            string[] student = new string[] { "Peter", "John", "Lisa" };
           
             //printing student name using for each loop
            foreach (string name in student)
            {
                Console.WriteLine(name);
            }
        }
    }

Output
Peter
John
Lisa

If we observe the above code , no indexing is used for printing the student names on console.
No condition is evaluated (boundary values to exit from the loop) for loop termination.

Notes

  • foreach loop doesn’t include initialization, termination, increment or decrement things.
  • it uses collection to take value by value and process them.
  • it avoids the errors that caused by incorrect index handling.
  • in foreach loop you can quit from loop using break keyword, and can continue the next iteration by skipping the execution of statements using continue keyword.
  • like for loop , for each loop cannot iterate in forward and backward directions. foreach loop can only iterate in forward direction.

C# Program to Print numbers in an array using for each loop.

C# Code

class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[] { 1,2,3,4,5,6 };
            foreach (int number in numbers)
            {
                Console.WriteLine(number);
            }
        }
    }

Output
1
2
3
4
5
6

Related Posts