Feedback for SYNMCQ46 problem

Learning course: Learn C++
Problem Link: CodeChef: Practical coding for everyone

Feedback

the answer to this problem should be 2 in my opinion but the answer they have provided is 3. please help.

@vanie0000

The provided answer, 3, is correct. As in a program, all code is executed sequentially.

In the following code block;

for (int i = 0 ; i <= 5 ; i = i + 2) {
    cout << "C++"<< endl;
    if(i == 4)
       break;
  }
  • Initially, i is zero.

Started the loop, C++ is printed. Now, we check the if condition. The condition is not satisfied, code proceeds.

  • Now i is incremented by +2, making it equals to two.

Again enter the loop, C++ is printed. Check the if condition, still False. Proceeds.

  • Now, i is again incremented by +2, making it equals to four.

Again we enter the loop. C++ is printed. Check the condition, its satisfied, break from the for loop.

  • Note: If the above code was re-arranged like this;
for (int i = 0 ; i <= 5 ; i = i + 2) {
    if(i == 4)
       break;
    cout << "C++"<< endl;
  }

then, the answer would have been 2, as the control would have broken from the for loop before cout could have been executed.

1 Like