• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does the counter skip one number can somebody explain  RSS feed

 
Elim Banda
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why does this code print even numbers instead of the all numbers from 0 to 7 can somebody please explain



Output

0
2
4
6
done


 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the variable i is getting incremented twice, once in the for-loop and once in the System.out.println (SOP).
 
Elim Banda
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do you mean the counter counts every time there is an iteration regardless of the condition of the for loop?
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your case, if i>=8 then the loop will exit without another increment of 'i'. So, no, it won't it won't increment regardless of the condition.
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "counter" you refer to is the variable named "i", right? And yes, it gets incremented every time that "++i" is executed, whether that's in line 4 or line 6.
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can disassemble a for loop to look like this (approximately)
 
Vaibhav Sagar
Ranch Hand
Posts: 35
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Elim, if you run your code with few additional System.out.println() then you'll realize the issue with your code. For e.g.-



What is happening is that you are incrementing your counter "i" twice, once inside your System.out.println(i++); and once in the end of the for loop for (int i = 0; i < 8; i++) {
i++ basically means i = i + 1 in your code and you are doing this twice.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!