0
please when I run this code, it produces an error message: timeout: monitored command dumped... For some test cases.
#include <iostream> using namespace std; int main() { int size = 0; int array[size]; int sum = 0; cin >> size; for(int i = 0; i < size; i++) { cin >> array[i]; } for(int j = 0; j < size; j++) { if(array[j] % 2 == 0) { sum += array[j]; } else { continue; } } cout << sum; return 0; }
2 Answers
+ 2
Your program is executed from top to bottom. What do you expect to happen at runtime if you first declare an array with "size" (which equals 0 at that point) elements and only later actually request a concrete value for "size"? You first need to get the value from the input stream before operating on/ with the variable it is stored in.
Also note VLA's are only compiler-specific extensions to the language and not standard C++. Using dynamic memory allocation or better std::vector<> might be more preferable.
0
thank you very much. I've learned something new. It worked like a charm