0
0
C++programming~10 mins

Array traversal in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print all elements of the array using a for loop.

C++
#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    for (int i = 0; i < n; i++) {
        std::cout << arr[[1]] << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Ai
Bn
C0
Darr
Attempts:
3 left
💡 Hint
Common Mistakes
Using the array name instead of the index.
Using the size variable as the index.
2fill in blank
medium

Complete the code to calculate the sum of all elements in the array.

C++
#include <iostream>

int main() {
    int arr[] = {10, 20, 30, 40};
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[[1]];
    }
    std::cout << sum << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
An
Bsum
Ci
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Adding the size variable instead of the element.
Using the sum variable as an index.
3fill in blank
hard

Fix the error in the loop condition to correctly traverse the array.

C++
#include <iostream>

int main() {
    int arr[] = {5, 10, 15};
    int n = sizeof(arr) / sizeof(arr[0]);
    for (int i = 0; i [1] n; i++) {
        std::cout << arr[i] << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A<
B<=
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes out-of-bounds access.
Using > or >= causes the loop to never run.
4fill in blank
hard

Fill both blanks to create a loop that prints elements at even indices only.

C++
#include <iostream>

int main() {
    int arr[] = {2, 4, 6, 8, 10, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    for (int i = [1]; i < n; i [2]) {
        std::cout << arr[i] << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A0
Bi += 2
Ci++
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 instead of 0.
Using i++ increments by 1, not 2.
5fill in blank
hard

Fill all three blanks to create a loop that prints elements in reverse order.

C++
#include <iostream>

int main() {
    int arr[] = {3, 6, 9, 12, 15};
    int n = sizeof(arr) / sizeof(arr[0]);
    for (int i = [1]; i [2] 0; i [3]) {
        std::cout << arr[i] << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
An - 1
B>
C--i
D++i
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 instead of the last index.
Using ++i instead of --i to go backwards.