Home » .Net

Explain foreach loop in C#

C# foreach loop: foreach is a special type of loop used in C#, which is used to access the elements of an array or collection, according to its name it can access each element of an array or collection.

There are three types of looping statements in C and C++ programming languages: for, while and do while. C# introduces a new looping statement that is known as foreach loop.

foreach is a special type of loop used in C#, which is used to access the elements of an array or collection, according to its name it can access each element of an array or collection.

Syntax:

foreach (var item in collection)
{
	//Statements               
}

Example:

foreach (int X in ARR)
{
	Console.Write(X+ “ ”;);                
}

In above example ARR is an array of elements and X is integer variables it accesses each element of array one by one and prints them with the help of foreach loop.

Consider the program:

using System;

namespace arrayEx
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] ARR = { 1, 2, 3, 4, 5 };

            Console.WriteLine("Elements are:");
            foreach (int X in ARR)
            {
                Console.Write(X + " ");
            }
            Console.WriteLine();
        }
    }
}

Output

Elements are:
1 2 3 4 5
Press any key to continue . . .

Above example demonstrate of use of Array class methods. Sort() method perform sorting, Reverse() method reverse the elements of array and Copy method is used to copy one array to another array.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.