This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes CS theory on a for loop... 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 "CS theory on a for loop..." Watch "CS theory on a for loop..." New topic
Author

CS theory on a for loop...

marque hudspeth
Greenhorn

Joined: Sep 11, 2008
Posts: 2
I have a class that has a for loop with 2 variables:

public class MultiFor {

public static void main(String[] args) {

for (int x = 0; x < 4; x++){

for (int y = 4; y > 2; y--) {
System.out.println(x + "" + y );
}

if (x==1) {
x++;
}

}
}
}

Here is the output:
04
03
14
13
34
33

The output is correct. However, I have noticed that when I remove the for loop with the y variable, i get this output:


public class MultiFor {

public static void main(String[] args) {



for (int x = 0; x < 4; x++){



System.out.println(x + "" );



if (x==1) {
x++;
}

}
}
}

output:
0
1
3

So my question is, why is the "value of x" looping/printing 6 times in the previous example, and only 3 times in the second example? Is it because the value of the "x for loop" looped through the "y for loop" AND the "x for loop"? Any input would be greatly appreciated.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

Welcome to JavaRanch!

The x loop loops three times; each time it loops, it executes the y loop. The y loop, in turn, executes twice each time it is entered; each execution of this loop prints one line. Therefore there are two lines printed for each execution of the x loop in the first example -- six lines altogether.


[Jess in Action][AskingGoodQuestions]
marque hudspeth
Greenhorn

Joined: Sep 11, 2008
Posts: 2
Ty, Jess. That was a swift and informative reply. Thank you very much.
 
 
subject: CS theory on a for loop...
 
Similar Threads
Simple 'for' loop question
Error: No public or protected classes found to documents 1 error
Bowled over by a simple code
Need Help With For Loops
Multi For Loop Question