0

Why is the output of the following for loop 2 2 2?

for (int i = 0, j = 2; i < 3; i++, j--) {
    System.out.print(i + j + " "); // why is this 2 2 2 ?
}
1
  • bcoz every time you are increasing value of i and decreasing value of j by 1...so net effect is no change in the i+j Commented Nov 7, 2015 at 13:58

2 Answers 2

3

i + j is always 2, as it does integer addition. So...

  1. 0 + 2 = 2
  2. 1 + 1 = 2
  3. 2 + 0 = 2

You can use j + "" + i + " ", which adds j to a string, instead of to a number.

Sign up to request clarification or add additional context in comments.

Comments

1

Because i + j is evaluated as sum of integers first, use i + "" + j so that they are evaluated as string concatenation.

    for (int i = 0, j = 2; i < 3; i++, j--) {
        System.out.print(i + "" + j + " "); // gives your 02 11 20
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.