Lesson 5.5:

C# foreach Loop - with programming example


Objective

What is foreach loop in c#?
Syntax and How it Works?
Programming example

What is foreach loop in c#?

foreach loop is another kind of looping constructs in c# which doesn't require initialization and other termination condition. It simply works on collection where it pick each item one by one until Travers all items in collection. It is very useful while working on array or collection.

How it Works?

The foreach loop traverse one by one all items in collection or array. When it finished traversing items the loops gets automatically terminated.

While(true) Loop

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace foreach_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] str = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday" };

            foreach (string day in str)
            {
                Console.WriteLine(day);
            }
            Console.WriteLine("End of Program");
            Console.ReadKey();
        }
    }
}

		  

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
End of Program

__

Explanation

In this programming example we have created an array as str which holds 5 days name. after that we have used foreach loop for getting information from array. In foreach loop there is string variable day which picks each item from array str and then print on console. When the all items of array has retrieved the loop terminated.

Summary

It this chapter you have learned about foreach loop in c#. foreach is such type of loop which doesn't required initialization or terminating condition. It works well on stored items as array or collection. In the next chapter you will about Nested Loop in c#.

BackNext