wood burning stoves*
The moose likes Beginning Java and the fly likes Nested For Loops - understanding them Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Nested For Loops - understanding them" Watch "Nested For Loops - understanding them" New topic
Author

Nested For Loops - understanding them

Steve Jensen
Ranch Hand

Joined: Sep 23, 2002
Posts: 126
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 ]

John Bonham was stronger, but Keith Moon was faster.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10

Code to print
one
one
two
two
would look like:

[ December 01, 2002: Message edited by: Marilyn de Queiroz ]

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8804
    
    5
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.


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Nested For Loops - understanding them
 
Similar Threads
Use of labelled statement in java ?
Arrays, For Loops,.....???
Evaluation of nested loops
three for Loops?
for loop