Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to traverse the array forward and print each element.
DSA Javascript
const arr = [1, 2, 3, 4]; for (let i = 0; i [1] arr.length; i++) { console.log(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes an index out of range error.
Using '>' or '>=' will not enter the loop.
✗ Incorrect
The loop should run while i is less than the array length to avoid going out of bounds.
2fill in blank
mediumComplete the code to traverse the array backward and print each element.
DSA Javascript
const arr = [5, 6, 7, 8]; for (let i = arr.length - 1; i [1] 0; i--) { console.log(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' misses the element at index 0.
Using '<' or '<=' will not run the loop correctly.
✗ Incorrect
The loop should run while i is greater than or equal to 0 to include the first element.
3fill in blank
hardFix the error in the code to traverse forward and print elements.
DSA Javascript
const arr = ['a', 'b', 'c']; for (let i = 0; i [1] arr.length; i++) { console.log(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes an error by accessing arr[arr.length].
Using '>' or '>=' will not run the loop.
✗ Incorrect
The loop condition must be 'i < arr.length' to avoid accessing undefined elements.
4fill in blank
hardFill both blanks to traverse backward and print elements.
DSA Javascript
const arr = [10, 20, 30, 40]; for (let i = arr.length - 1; i [1] 0; i[2]) { console.log(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' or '++' will cause the loop to run incorrectly or infinitely.
✗ Incorrect
The loop should continue while i >= 0 and decrement i each time using '--'.
5fill in blank
hardFill all three blanks to create a forward traversal that prints only even numbers.
DSA Javascript
const arr = [1, 2, 3, 4, 5, 6]; for (let i = 0; i [1] arr.length; i[2]) { if (arr[i] [3] 2 === 0) { console.log(arr[i]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '--' will cause an infinite loop.
Using '<=' will cause out of bounds error.
Using other operators instead of '%' will not correctly check even numbers.
✗ Incorrect
The loop runs while i < arr.length, increments i with '++', and checks if arr[i] % 2 === 0 for even numbers.
