C# Loop Through an Array
Arrays can be traversed using loops to perform operations on each element. The most common loops used are the for loop and the foreach loop.
Key Topics
1. Using a For Loop
Example: Iterating with a For Loop
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Output:
1
2
3
4
5
2
3
4
5
2. Using a Foreach Loop
Example: Iterating with a Foreach Loop
string[] colors = { "Red", "Green", "Blue" };
foreach (string color in colors)
{
Console.WriteLine(color);
}
Output:
Red
Green
Blue
Green
Blue
3. Comparing For and Foreach Loops
The for loop gives you access to the index, which can be useful for certain operations. The foreach loop is more concise and easier to read when you don't need the index.
Example: Using Index in a For Loop
for (int i = 0; i < colors.Length; i++)
{
Console.WriteLine($"Index {i}: {colors[i]}");
}
Key Takeaways
- Use a
forloop when you need to work with element indices. - Use a
foreachloop for cleaner code when indices are not needed. - Looping allows you to perform operations on each array element.
- Understanding both loops enhances your ability to manipulate arrays effectively.