1

I want to know the difference between post-increment and pre-increment, basically, I wrote two same codes together by just changing the variables to check whether there is any difference in post and pre-increment. but it's the same??

int tableOf = 4;
    for (int i = 1; i <= 10; ++i) {
        System.out.println(tableOf * i);
        System.out.println(i);
        }
        int tableof = 4;
        for (int y = 1; y <= 10; y++) {
            System.out.println(tableof * y);
            System.out.println(y);
        }
Vyom Yadav
  • 145
  • 13
  • 1
    Try `int x = 0; System.out.println(x++); System.out.println(x);` and `int x = 0; System.out.println(++x); System.out.println(x);` – QBrute Oct 10 '20 at 14:47
  • but then why is code running the same after pre and post increment – Vyom Yadav Oct 10 '20 at 14:48
  • in the first its i++ and second ++y but still output is same – Vyom Yadav Oct 10 '20 at 14:48
  • @VyomYadav Because the expression is a standalone statement in this context. 1. Try the code in QBrute's comment. 2. Read the Stackoverflow post referenced by Eklavya's comment. – MC Emperor Oct 10 '20 at 14:53
  • In your code, it doesn't matter which one you are using since you are doing only one operation increment. If you combile with another operation assigning/printing then you can understand the order matters.(assign first or increment first) – Eklavya Oct 10 '20 at 14:53
  • The value returned by the third statement in the loop is never used. `i` starts at 1, gets incremented and returns 2. The `i` is left at 2. `y` starts at 1, gets incremented but returns 1. The `y` is left at 2. *The value used in the comparison is not affected by the value returned in the third statement.* – matt Oct 10 '20 at 14:56
  • Any other simpler explanations, I am not able to understand it? – Vyom Yadav Oct 10 '20 at 16:26
  • Why do you think it would be different? What changes between the two loops would cause a difference, and what is the difference you would observe. – matt Oct 11 '20 at 08:08
  • Also, can you edit your question to fix your brackets? Right now you have two for loops that appear to be nested, but the way you describe it, they probably shouldn't be. – matt Oct 11 '20 at 08:09
  • @matt and everybody else found where I am going wrong by trying different examples, thanks a lot. – Vyom Yadav Oct 11 '20 at 10:22

1 Answers1

1

post-increment uses the value and increments it after usage. pre-increment first increments and then uses the value. in the example of a for-loop the procedure is

i = i++;

or

i = ++i;

in this case it doesnt matter if you are using pre or post in the end i is incremented by 1.

An relevant example would be an addition:

int a = 1;
int b = 2;



int c = a + b++; -> c = 3

or

int c = a + ++b; -> c = 4
Twelve
  • 236
  • 1
  • 5