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 arr[] = {1, 2, 3, 4, 5};
int n = 5;
for (int i = 0; i [1] n; i++) {
std::cout << arr[i] << " ";
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i <= n causes out-of-bounds access.
Using i > n or i >= n causes the loop to never run.
✗ Incorrect
The loop should run from 0 up to but not including n, so i < n is correct.
2fill in blank
mediumComplete the code to traverse the array backwards and print elements.
DSA C++
int arr[] = {10, 20, 30, 40, 50};
int n = 5;
for (int i = n - 1; i [1] 0; i--) {
std::cout << arr[i] << " ";
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i < 0 causes the loop to never run.
Using i <= 0 stops the loop too early.
✗ Incorrect
The loop starts at n-1 and decrements until i >= 0 to include index 0.
3fill in blank
hardFix the error in the code to correctly print every second element of the array.
DSA C++
int arr[] = {5, 10, 15, 20, 25, 30};
int n = 6;
for (int i = 0; i [1] n; i += 2) {
std::cout << arr[i] << " ";
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i <= n causes out-of-bounds access.
Using i > n or i >= n causes the loop to never run.
✗ Incorrect
To avoid out-of-bounds access, the loop should run while i is less than n, so i < n is correct.
4fill in blank
hardFill both blanks to create a loop that prints elements at odd indices.
DSA C++
int arr[] = {2, 4, 6, 8, 10, 12};
int n = 6;
for (int i = [1]; i [2] n; i += 2) {
std::cout << arr[i] << " ";
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 prints even indices.
Using i <= n causes out-of-bounds access.
✗ Incorrect
Start at index 1 to get odd indices, and loop while i < n to avoid out-of-bounds.
5fill in blank
hardFill all three blanks to create a loop that prints elements divisible by 3.
DSA C++
int arr[] = {3, 5, 6, 7, 9, 12};
int n = 6;
for (int i = 0; i [1] n; i++) {
if (arr[i] [2] 3 [3] 0) {
std::cout << arr[i] << " ";
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i <= n causes out-of-bounds access.
Using == instead of % causes syntax errors.
Checking for non-zero remainder instead of zero.
✗ Incorrect
Loop while i < n to stay in bounds, use % to check remainder, and == 0 to check divisibility.
