+ 3

does anyone have a good example of prefix and postfix increments?

I understand the difference of prefix and postfix, but am having a difficult time understanding why you would use them in certain situations.

9th Oct 2016, 8:10 PM
Matthew Sutton
Matthew Sutton - avatar
4 odpowiedzi
+ 6
for(int i = 1; i <= 10; i++) //post System.out.println(i++); output will be: 1 3 5 7 9 means print i, then add 1 to i after printing, which means if printed i was 1, after printing i will be 2 for(int i = 1; i <= 10; i++) //pre System.out.println(++i); output will be: 2 4 6 8 10 means add 1 to i then print new i, which means if i was 1 before printing, add 1 then print the new i which will be 2
9th Oct 2016, 8:34 PM
Flo
+ 4
https://code.sololearn.com/c68JVx3xS9B0/?ref=app Check this. It is self explanatory. It might be helpful for you
15th Feb 2017, 1:48 PM
Kommoju Sunil Kumar
Kommoju Sunil Kumar - avatar
+ 1
plzz explain loop how work it??
11th Oct 2016, 4:53 AM
Javed
Javed - avatar
+ 1
Javed, if you are asking about the for loops I used, then using second loop(pre), it says 1. starting from 1(i=1), check if i is not exceeding 10(i<=10), if it doesn't, go inside the loop. 2. inside the loop, it says add 1 to i(i++ or ++i is same as i=i+1) before you print, having ++ before i means, do the increment before i is used in this statement. So at this moment i=2, 3. then we go back to i++ in (int i=1; i<=10;i++), adding 1 to i(i++) and checking if it is not exceeding 10(i<=10), if i doesn't exceed 10 we go inside loop and repeat step 2 then step 3 until i in step 3 is more than 10, then the loop will stop. If we used first loop(post), step 2 will change to, print i, after you print add 1 to i, ++ after i means, use the statement first, then increment i. So when printing i is equal to 1, after printing, i is equal to 2 hopefully I answered your question
11th Oct 2016, 3:51 PM
Flo