Foreach loop in C#
Dec 22, 2020 08:11 0 Comments C# (C-Sharp) PARTH

                       Foreach loop in C#  

The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list.   Important points regarding foreach loop – Please enclose the statements of foreach loop in curly brackets. You should declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name instead of declaring and initializing a loop counter variable. You can use the loop variable you created in the loop body.

  Syntax:

foreach(datatype variablename in collectionname)

{   

   // execute the logic

}  

  Let us see an example –

using System;

  class Program

{      

 static public void Main()   

 

  {   

      int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

          foreach(int items in arr)       

  {             

Console.WriteLine(items);        

 }    

 }

}   Output : 1 2 3 4 5 6 7 8 9 0

C-foreach-Loop-m.jpg

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect