Challenge - 5 Problems
Array Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of array traversal with pointer arithmetic
What is the output of the following C++ code?
C++
#include <iostream> int main() { int arr[] = {10, 20, 30, 40, 50}; int *p = arr; for (int i = 0; i < 5; ++i) { std::cout << *(p + i) << " "; } return 0; }
Attempts:
2 left
💡 Hint
Pointer arithmetic moves through the array elements in order.
✗ Incorrect
The pointer p points to the first element of the array. Adding i moves the pointer to the next elements. Dereferencing *(p + i) prints each element in order.
❓ Predict Output
intermediate2:00remaining
Output of array traversal with range-based for loop
What will this C++ program print?
C++
#include <iostream> int main() { int arr[] = {1, 2, 3, 4, 5}; for (int x : arr) { std::cout << x * 2 << " "; } return 0; }
Attempts:
2 left
💡 Hint
The loop multiplies each element by 2 before printing.
✗ Incorrect
The range-based for loop goes through each element in arr. Each element is multiplied by 2 and printed with a space.
❓ Predict Output
advanced2:00remaining
Output of nested array traversal
What is the output of this nested loop traversing a 2D array?
C++
#include <iostream> int main() { int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { std::cout << matrix[i][j] << " "; } } return 0; }
Attempts:
2 left
💡 Hint
The outer loop goes through rows, inner loop through columns.
✗ Incorrect
The code prints all elements row by row: first row elements then second row elements.
❓ Predict Output
advanced2:00remaining
Output of array traversal with incorrect loop condition
What happens when this code runs?
C++
#include <iostream> int main() { int arr[] = {5, 10, 15}; for (int i = 0; i <= 3; ++i) { std::cout << arr[i] << " "; } return 0; }
Attempts:
2 left
💡 Hint
The loop goes one step beyond the array size.
✗ Incorrect
The loop accesses arr[3], which is out of bounds. This causes undefined behavior: it may print garbage or cause a runtime error.
🧠 Conceptual
expert2:00remaining
Identifying the number of elements traversed
Given the code below, how many elements will be printed?
C++
#include <iostream> int main() { int arr[4] = {7, 14, 21, 28}; int *ptr = arr + 1; for (int i = 0; i < 3; ++i) { std::cout << *(ptr + i) << " "; } return 0; }
Attempts:
2 left
💡 Hint
Pointer starts at second element, loop runs 3 times.
✗ Incorrect
Pointer ptr points to arr[1]. Loop runs 3 times printing arr[1], arr[2], arr[3]. So 3 elements printed.