+ 4

C++ code question 3

What is the output of this code? int p; for (int a = 0; a < 1; a += 3){ p = a; } cout << p; my answer is 3 but the right answer is 0. It's really bewildering...🤔 waiting your wise idea ☺️

3rd Mar 2018, 5:27 PM
Eros boulay
Eros boulay - avatar
3 odpowiedzi
+ 4
@Jayden the loop runs 1 time with i=0. The order of for-loops is: 1. check condition 2. run code if condition is met 3. increment the running variable -> repeat steps In this code the loop starts with i=0, checks if i<1(step 1), runs the code (step 2), increments i by 3 (step 3), checks the condition (repeat -> step 1) and breaks the loop.
3rd Mar 2018, 5:59 PM
Alex
Alex - avatar
+ 2
It's really a wise idea 👍
3rd Mar 2018, 5:31 PM
Eros boulay
Eros boulay - avatar
0
hi
6th Mar 2018, 3:51 AM
Firuz