• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

For Loop Confusing  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Recently, I started learning Java and now I have some trouble understanding line of a code.



My question is: how this for loop affect to count variable? Okay, I set it inside of for loop block, but here I am working with int i variable, not with count.Int i go through loop and stops when it reach 10.
 
Ranch Hand
Posts: 172
1
Android Java Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

how this for loop affect to count variable?


count will be increased if variable i is less or equal to 10.  
 
Marshal
Posts: 63454
207
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to avoid <= and starting with 1. The basic form of a for loop is this:-As you will see, that loop will run 10×; the loop you wrote runs 11×. In some circumstances you will need to alter the basic form, but always use that as a starting point.
 
lowercase baba
Posts: 12725
51
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This looks like you are a victim of an "off by one" error - sometimes called a "fence post" error.  It's a common problem.

Your loop actually runs 11 times.  it runs when i is equal to 0, 1,2,3...and 10.  it stops when I is 11.  If you count the numbers in the sequence 0 - 10, you will see there are eleven of them.

the term "fence post" comes from a problem determining how many posts you need to build a fence X feet long with a post every Y feet.  
 
The City calls upon her steadfast protectors. Now for a tiny ad:
ScroogeXHTML 8.2 - easy to use RTF to HTML converter library
https://coderanch.com/t/707504/ScroogeXHTML-RTF-HTML-XHTML-converter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!