Home > Back-end >  Why does it print 12345 not 01234?
Why does it print 12345 not 01234?

Time:10-25

It has to be output like this 01234

for(int i = 0;i < 5; i  , System.out.print(i));

or

for(int i = 0;i < 5; System.out.print(i))
    i  ;

Output: 12345

CodePudding user response:

for(int i = 0;i < 5; System.out.print(i))
    i  ;

Is equivalent to the following while loop:

{
  int i = 0;
  while (i < 5) {
    i  = 1;
    System.out.print(i);
  }
}

i is always incremented before it is printed. Same goes for i , System.out.print(i): i is already incremented before it is printed. And I don't need to mention that 0 1 = 1.

CodePudding user response:

It's pretty easy, you just need to understand what you're writing. It should go like:

for(int i=0;i<5;i  ){ //"i" is increased at the end of the loop
    System.out.print(i) //prints "i", which is zero and will increase up to 4
}

And that's it

  • Related