Challenge - 5 Problems
Array Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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] + " "); }
Attempts:
2 left
💡 Hint
Remember that Console.Write prints without a newline and the loop prints each element followed by a space.
✗ Incorrect
The for loop iterates over each element in the array and prints it followed by a space, resulting in '1 2 3 '.
❓ Predict Output
intermediate2: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]);
}Attempts:
2 left
💡 Hint
Each fruit's first character is printed without spaces.
✗ Incorrect
The foreach loop prints the first character of each fruit, resulting in 'abc'.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
The for loop adds all elements once, then the foreach adds them again.
✗ Incorrect
The sum is 2+4+6 = 12 from the for loop, then 12 more from the foreach, total 24.
❓ Predict Output
advanced2: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 + " "); }
Attempts:
2 left
💡 Hint
Foreach variable is read-only copy, modifying it does not change the array.
✗ Incorrect
The first loop prints doubled values but does not change the array. The second loop prints original values.
🧠 Conceptual
expert3: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?
Attempts:
2 left
💡 Hint
Think about how foreach handles the loop variable.
✗ Incorrect
In C#, foreach assigns each element's value to the loop variable as a copy. Modifying the variable does not change the original array element.