Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • 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
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Nested For Loops - understanding them  RSS feed

 
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been trying to understand just how nested for loops work , so I thought i'd devise a simple one of my own, as in the code below:-

The thing is, I think the comments i've inserted next to the loops are indicative of their function , but, for example, how can I change this code, so that the word 'two', appears twice, i.e., like
one
one
two
two
I suppose this all stems from my misunderstanding of the whole concept, right?
(Marilyn added code tags to preserve formatting)
[ December 01, 2002: Message edited by: Marilyn de Queiroz ]
 
Sheriff
Posts: 9092
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Code to print
one
one
two
two
would look like:

[ December 01, 2002: Message edited by: Marilyn de Queiroz ]
 
author
Posts: 8981
19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice that Marilyn 'unnested' the inner-most for loop to get 'two' to print twice in a row. Think of the nested loops as wheels on an odometer. The outer loop is the most significant number (leftmost), and the inner-most loop is the least significant (in this case the tenths of a mile). The farther right the digit, the more often it spins before the leftmost (outer) loops will increment.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!