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

Array iteration with for and foreach in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of for loop iterating over an array
What is the output of the following C# code?
C Sharp (C#)
int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.Length; i++)
{
    Console.Write(numbers[i] + " ");
}
A0 1 2
B1 2 3
C123
D1 2 3 4
Attempts:
2 left
💡 Hint
Remember that Console.Write prints without a newline and the loop prints each element followed by a space.
Predict Output
intermediate
2:00remaining
Output of foreach loop with array
What will this C# code print?
C Sharp (C#)
string[] fruits = {"apple", "banana", "cherry"};
foreach (string fruit in fruits)
{
    Console.Write(fruit[0]);
}
Aabc
Bapplebanana cherry
Ca b c
Dapple
Attempts:
2 left
💡 Hint
Each fruit's first character is printed without spaces.
Predict Output
advanced
2:00remaining
Value of sum after mixed iteration
What is the value of sum after running this code?
C Sharp (C#)
int[] values = {2, 4, 6};
int sum = 0;
for (int i = 0; i < values.Length; i++)
{
    sum += values[i];
}
foreach (int v in values)
{
    sum += v;
}
A6
B12
C18
D24
Attempts:
2 left
💡 Hint
The for loop adds all elements once, then the foreach adds them again.
Predict Output
advanced
2:00remaining
Output of modifying array inside foreach
What happens when this code runs?
C Sharp (C#)
int[] nums = {1, 2, 3};
foreach (int n in nums)
{
    n = n * 2;
    Console.Write(n + " ");
}
Console.WriteLine();
foreach (int n in nums)
{
    Console.Write(n + " ");
}
A
2 4 6 
1 2 3 
B
2 4 6 
2 4 6 
C
1 2 3 
1 2 3 
DCompilation error
Attempts:
2 left
💡 Hint
Foreach variable is read-only copy, modifying it does not change the array.
🧠 Conceptual
expert
3:00remaining
Why does modifying array elements inside foreach cause error?
Consider this code snippet: int[] arr = {1, 2, 3}; foreach (int x in arr) { x = x + 1; } Why does this code not modify the array elements?
ABecause the compiler automatically resets the array after the loop finishes.
BBecause arrays in C# are immutable and cannot be changed after creation.
CBecause the foreach variable 'x' is a copy of each element, not a reference, so changes don't affect the array.
DBecause the foreach loop does not allow any statements inside its block.
Attempts:
2 left
💡 Hint
Think about how foreach handles the loop variable.