for and foreach loops when iterating over an array in C#?for loop uses an index to access array elements, allowing modification of elements and control over iteration.
foreach loop directly accesses each element without an index, is simpler, but does not allow modifying the array elements directly.
for loop to print all elements of an integer array numbers.for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}foreach loop improve code readability when iterating arrays?foreach hides the index management and directly gives each element, making the code shorter and easier to read.
foreach loop in C#? Why or why not?No, you cannot modify the elements directly inside a foreach loop because the loop variable is read-only and represents a copy of the element.
for loop?You get a System.IndexOutOfRangeException error because the index is invalid and outside the array limits.
The for loop allows access by index, so you can modify array elements directly.
foreach loop provide when iterating an array?foreach gives you each element directly, without the index.
Arrays have a Length property (no parentheses) to get their size.
for loop?Accessing outside array bounds throws IndexOutOfRangeException.
foreach is simpler and clearer for reading elements.
for and foreach loops in C#.for loop over a foreach loop for array iteration.