0

Why the answers are being different only by changing the position of break function? "alert show 'sum=1tum=3"

var sum =0; for (i=0;i<=3;i++){ if (i==2){ break ;} sum+=i; } var tum =0; for (e=0;e<=3;e++){ tum+=e; if (e==2){ break ;} } alert ("sum="+sum+"tum="+ tum);

29th Sep 2020, 11:50 AM
RD:programmer
RD:programmer - avatar
6 Réponses
+ 1
The first one sum doesn't increase by 2 because the loop already breaks before it. The second one tum does because it increases before the loop breaks. The order matters.
29th Sep 2020, 11:53 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
its not changing position of the break statement. its moving the "add to sum" statement. for every loop in the three loops i is incremented by 1 and AFTER that the sum is incremented by i. It starts at 0, then its 1, then when i becomes 2. But before it can add that 2 to the sum, it breaks so sum == 1. The second for loop adds to tum BEFORE the break check, so when e is 2, it adds e to tum BEFORE breaking, wthats why its 3, 0+1+2 = 3.
29th Sep 2020, 11:58 AM
Slick
Slick - avatar
+ 1
e=0 tum=0 e=1 tum+=e (tum=1) 1 e=2 + tum+=e (tum=3) 2 e=3 + tum+=e (tum=6) 3 =6
29th Sep 2020, 12:09 PM
Slick
Slick - avatar
0
It is still hard to understand 😔
29th Sep 2020, 11:56 AM
RD:programmer
RD:programmer - avatar
0
Please friends ,keep explaining me step by step 🙏🙏🙏🙏🙏🙏
29th Sep 2020, 11:57 AM
RD:programmer
RD:programmer - avatar
0
I write "e<=3 "so the answer seems 0+1+2+3=6 and then break .after it how the answer reach to 3 from 6 .🙏🙏🙏
29th Sep 2020, 12:05 PM
RD:programmer
RD:programmer - avatar