+ 3
Can anyone give me it's explanation?
11 Antworten
+ 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
+ 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×.
+ 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.
+ 2
Cyan why n will be decreased once will it is not a part of loop?
+ 2
Atul
It is decreased because of incremention.
--n
is the same with
n = n - 1
+ 2
Cyan I understood what you explained. Actually I haven't gone through the mistake which you did😅
+ 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.
+ 1
Cyan not that but n not been in the part of loop decreased by 1. Why?
+ 1
Cyan thanks , but this stuff is a rule in Java?
+ 1
Thanks Cyan got it
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;
}