C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The code is a complete C# console program. The string array is initialized and four values are inserted into it.
Foreach: A foreach-loop iterates over each string in the array. The four values are printed to the console.
C# program that loops over string array
using System;
class Program
{
static void Main()
{
string[] arr = new string[4]; // Initialize.
arr[0] = "one"; // Element 1.
arr[1] = "two"; // Element 2.
arr[2] = "three"; // Element 3.
arr[3] = "four"; // Element 4.
// Loop over strings.
foreach (string s in arr)
{
Console.WriteLine(s);
}
}
}
Output
one
two
three
four
Here: This example initializes a string array with four elements with Spanish numbers.
For 1: Here we loop over the string array with the for-loop construct, going from start to end. The loop starts at 0.
For 2: The second loop walks over the strings backwards. It starts at the last index, which is one less than the length. It decrements.
StringsC# program that loops with for-loop
using System;
class Program
{
static void Main()
{
string[] arr = new string[4]; // Initialize.
arr[0] = "uno"; // First element.
arr[1] = "dos"; // Second.
arr[2] = "tres"; // Third.
arr[3] = "cuatro"; // Fourth.
// Loop over strings.
for (int i = 0; i < arr.Length; i++)
{
string s = arr[i];
Console.WriteLine(s);
}
// Loop over strings backwards.
for (int i = arr.Length - 1; i >= 0; i--)
{
string s = arr[i];
Console.WriteLine(s);
}
}
}
Output
uno
dos
tres
cuatro
cuatro
tres
dos
uno
Foreach: Simpler syntax makes fewer typos likely. You can use custom enumerators. You can change the internal looping mechanism.
For: Usually equal in speed or faster. You can check the previous or next elements. You can loop in reverse.