cppintermediate10 minutes
Predict the Output: Array Transformation and Loop Logic in C++
Analyze the given C++ code snippet that performs multiple array transformations and loop operations. Predict the final output printed by the program without running it.
Challenge prompt
Consider the following C++ code: int arr[] = {2, 4, 6, 8}; int n = 4; for (int i = 0; i < n; i++) { arr[i] = arr[i] + i; } for (int i = n - 1; i > 0; i--) { arr[i] = arr[i] - arr[i - 1]; } for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } What is the output of this program when executed? Explain your reasoning.
Guidance
- • Step through each loop iteration carefully, tracking how the array elements change.
- • Remember the effect of modifying array elements in place and how that influences subsequent calculations.
Hints
- • After the first loop, the array elements are incremented by their index positions.
- • In the second loop, each element is updated based on the difference with the previous element, starting from the end.
Starter code
int arr[] = {2, 4, 6, 8};
int n = 4;
for (int i = 0; i < n; i++) {
arr[i] = arr[i] + i;
}
for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i] - arr[i - 1];
}
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
Expected output
2 2 0 2
Core concepts
array manipulationfor loopsin-place modificationbasic arithmetic operations
Challenge a Friend
Send this duel to someone else and see if they can solve it.