cppintermediate10 minutes
Predict Output: Logical Array State Manipulation in C++
Analyze a C++ function manipulating a boolean array with combined loop and conditional logic to determine what the final output will be.
Challenge prompt
Given the following C++ code snippet, predict what the program will print to standard output. Consider carefully how the boolean array is updated inside the loop and what printArray outputs based on that state.
Guidance
- • Trace each iteration of the loop step-by-step, updating the array elements as indicated.
- • Pay attention to the order of evaluations inside the loop and conditions that alter the array.
- • Recall how boolean values are printed as integers (0 or 1) in C++ when using std::cout.
Hints
- • Consider the initial state of the array and how it changes precisely on each loop iteration.
- • Remember that arr[(i+1) % 5] targets the next element circularly, so updates affect subsequent iterations.
- • Focus on how the condition sets arr[i] before printing; this shapes the output pattern.
Starter code
#include <iostream>
using namespace std;
void printArray(bool arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
bool arr[5] = {false, true, false, true, false};
for (int i = 0; i < 10; i++) {
arr[(i + 1) % 5] = arr[i % 5] && !arr[(i + 2) % 5];
arr[i % 5] = !arr[i % 5];
printArray(arr, 5);
}
return 0;
}Expected output
1 1 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0
Core concepts
boolean logicarraysloops
Challenge a Friend
Send this duel to someone else and see if they can solve it.