Foreach loops


A Foreach loop is used for getting items from an array. That makes this process so easier than using a for loop.

Foreach loops are defined like this:

foreach (type variable in array)
{
  //Code
}

The loop will get the array length and loop through the elements of array.

Example:

string[] programming = {"C++", "C#", "CPython", "C", "Java", "JavaScript"}; //An array

foreach (string language in programming)
{
   Console.WriteLine(language);
}

This will output every item in programming.

Exercise

In this exercise, you must output every item in parts with a foreach loop that has part as a variable.


Copyright © learncs.org. Read our Terms of Use and Privacy Policy