• 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
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

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: 201
2
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: 64172
215
  • 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: 12738
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.  
 
I just had the craziest dream. This tiny ad was in it.
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!