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 Java
int[] arr = {1, 2, 3, 4, 5};
for (int [1] = 0; [1] < arr.length; [1]++) {
System.out.print(arr[[1]] + " ");
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not matching the loop condition causes errors.
Starting the loop variable at 1 instead of 0 skips the first element.
✗ Incorrect
The loop variable is commonly named 'i' to iterate over array indices from 0 to length-1.
2fill in blank
mediumComplete the code to traverse the array backwards and print elements.
DSA Java
int[] arr = {10, 20, 30, 40, 50};
for (int i = arr.length - 1; [1] >= 0; i--) {
System.out.print(arr[i] + " ");
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable in the condition than in the initialization.
Incorrect loop condition causing infinite loops.
✗ Incorrect
The loop variable 'i' is used to traverse from the last index down to 0.
3fill in blank
hardFix the error in the code to sum all elements of the array.
DSA Java
int[] numbers = {2, 4, 6, 8};
int sum = 0;
for (int i = 0; i < numbers.length; [1]++) {
sum += numbers[i];
}
System.out.println(sum);Attempts:
3 left
💡 Hint
Common Mistakes
Incrementing a variable not used in the loop condition.
Forgetting to increment the loop variable causing infinite loops.
✗ Incorrect
The loop variable 'i' must be incremented to avoid infinite loop and correctly sum elements.
4fill in blank
hardFill both blanks to create a loop that prints only even numbers from the array.
DSA Java
int[] nums = {1, 2, 3, 4, 5, 6};
for (int [1] = 0; [2] < nums.length; [1]++) {
if (nums[[1]] % 2 == 0) {
System.out.print(nums[[1]] + " ");
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in loop parts causing errors.
Mismatching loop variable and array index variable.
✗ Incorrect
The loop variable 'i' is used consistently in initialization and condition to traverse the array.
5fill in blank
hardFill all three blanks to create a loop that prints elements at odd indices.
DSA Java
int[] data = {5, 10, 15, 20, 25, 30};
for (int [1] = 1; [2] < data.length; [3] += 2) {
System.out.print(data[[1]] + " ");
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in loop parts.
Incrementing by 1 instead of 2 causing wrong output.
✗ Incorrect
The loop variable 'i' starts at 1, condition uses 'i', and increments by 2 to access odd indices.
