0
0
C Sharp (C#)programming~5 mins

Array iteration with for and foreach in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the main difference between 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.

Click to reveal answer
beginner
Write a simple for loop to print all elements of an integer array numbers.
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
Click to reveal answer
beginner
How does the 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.

Click to reveal answer
intermediate
Can you modify elements of an array inside a 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.

Click to reveal answer
beginner
What happens if you try to access an array element with an index outside its bounds in a for loop?

You get a System.IndexOutOfRangeException error because the index is invalid and outside the array limits.

Click to reveal answer
Which loop is best when you need to modify elements of an array during iteration?
Afor
Bforeach
Cwhile
Ddo-while
What does foreach loop provide when iterating an array?
AOnly index
BIndex and element
COnly element
DNeither index nor element
What property gives the length of an array in C#?
ALength()
BLength
CSize
DCount
What error occurs if you use an invalid index in a for loop?
AIndexOutOfRangeException
BNullReferenceException
CArgumentException
DInvalidOperationException
Which loop is simpler for just reading all elements without changing them?
Afor
Bdo-while
Cwhile
Dforeach
Explain how to iterate over an array using both for and foreach loops in C#.
Think about how you count items versus how you just look at each item.
You got /4 concepts.
    Describe when you would choose a for loop over a foreach loop for array iteration.
    Consider if you need to change or just read the items.
    You got /4 concepts.