We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Wednesday, June 17, 2015

Foreach in c#

The foreach loop is used with arrays and collections. The foreach loop accesses arrays and collections in a unique way without using counters. A program iterates over a collection. The index of each element is not needed. Only the elements are needed. With foreach we access just the elements.


for loop uses counter while foreach can be used without counters.
Example1
The program prints array elements using foreach loop.

class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            foreach (int i in arr)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();

        }


    }
OUTPUT:
1
2
3
4
5
6
7
8
9

Example2
class Program   
{       
static void Main()       
{
            string[] str = { "dog", "cat", "rat" };
            foreach (string s in str)
            {
                Console.WriteLine(s);
            }       
}   
}
OUTPUT: dog cat rat

No comments: