Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print all elements of the array using a for loop.
DSA C#
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i [1] numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes an IndexOutOfRangeException.
Using > or >= will not enter the loop.
✗ Incorrect
The loop should run while i is less than numbers.Length to avoid going out of bounds.
2fill in blank
mediumComplete the code to traverse the array backwards using a for loop.
DSA C#
int[] values = {10, 20, 30, 40};
for (int i = values.Length - 1; i [1] 0; i--)
{
Console.WriteLine(values[i]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using > will skip the first element at index 0.
Using < or <= will cause the loop to not run.
✗ Incorrect
The loop should continue while i is greater than or equal to 0 to include the first element.
3fill in blank
hardFix the error in the code to correctly print every second element starting from the first.
DSA C#
int[] data = {5, 10, 15, 20, 25};
for (int i = 0; i [1] data.Length; i += 2)
{
Console.WriteLine(data[i]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes an exception when i equals data.Length.
Using > or >= will not run the loop.
✗ Incorrect
Use < to avoid going out of bounds when accessing data[i].
4fill in blank
hardFill both blanks to create a loop that prints elements at odd indices only.
DSA C#
int[] arr = {2, 4, 6, 8, 10, 12};
for (int i = [1]; i [2] arr.Length; i += 2)
{
Console.WriteLine(arr[i]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 prints even indices.
Using <= causes IndexOutOfRangeException.
✗ Incorrect
Start at index 1 and continue while i is less than arr.Length to print odd indices.
5fill in blank
hardFill all three blanks to create a loop that sums elements at even indices.
DSA C#
int[] nums = {3, 7, 1, 9, 5};
int sum = 0;
for (int i = [1]; i [2] nums.Length; i [3] 2)
{
sum += nums[i];
}
Console.WriteLine(sum);Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 sums odd indices.
Using <= causes out of range error.
Using i++ increments by 1, not 2.
✗ Incorrect
Start at 0, continue while i < nums.Length, and increment i by 2 using += to sum even indices.
