+ 3

Can anyone give me it's explanation?

https://code.sololearn.com/cimI8GwzjVQ0/?ref=app

10th Feb 2021, 11:58 AM
Atul [Inactive]
11 Respostas
+ 10
Basically , --n is not part of the for loop because it does not have curly brackets to include multiline statement Remember that this seems one line but this is actually two lines: m++; --n; As semicolons indicates the end of the line. Therefore m will be incremented 4 times (loop iterated 4 times). While n will be incremented by -1 only one time. 2 ---> 6 14 ---> 13 This code may help you understand better. https://code.sololearn.com/cP94Qm8dSzwk/?ref=app
10th Feb 2021, 12:12 PM
noteve
noteve - avatar
+ 4
public class Program { public static void main(String[] args) { int m=2; int n=14; for(int i=1;i<5;i++) m++;--n; System.out.println (m); System.out.println (n); } } Its equivalent to the code below public class Program { public static void main(String[] args) { int m=2; int n=14; for(int i=1;i<5;i++) m++; --n; System.out.println (m); System.out.println (n); } } So only the m++ is part the loop because you have not used { } to scope the body of your loop only the first one instruction after the loop header is considered as part of the loop. So m++ is looped 4× and after the other instructions are all executed one time so --n is executed 1×.
11th Feb 2021, 11:58 AM
Elon
Elon - avatar
+ 4
Atul Are you talking about why m is 1 in my previous example? That is a typographical error, It should be 2 and the iteration is 4 times not 5. I apologise if such typographical errors confused you.
11th Feb 2021, 12:00 PM
noteve
noteve - avatar
+ 2
Cyan why n will be decreased once will it is not a part of loop?
10th Feb 2021, 12:06 PM
Atul [Inactive]
+ 2
Atul It is decreased because of incremention. --n is the same with n = n - 1
10th Feb 2021, 12:07 PM
noteve
noteve - avatar
+ 2
Cyan I understood what you explained. Actually I haven't gone through the mistake which you did😅
11th Feb 2021, 12:05 PM
Atul [Inactive]
+ 1
Adding the indentation, the for loop becomes: for(int i = 1 ; i < 5 ; i++) m++; --n; Now you can read it clearly, only m is affected by the loop which loops 4 times.
10th Feb 2021, 12:03 PM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
+ 1
Cyan not that but n not been in the part of loop decreased by 1. Why?
10th Feb 2021, 12:10 PM
Atul [Inactive]
+ 1
Cyan thanks , but this stuff is a rule in Java?
10th Feb 2021, 12:17 PM
Atul [Inactive]
+ 1
Thanks Cyan got it
10th Feb 2021, 12:55 PM
Atul [Inactive]
0
To make both variables change the values multiple times in the loop, you should modify the code so that : for(int i=1;i<5;i++) { m++; --n; }
12th Feb 2021, 5:23 AM
Bartek RocƂawski
Bartek RocƂawski - avatar