File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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: 24187
    
  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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: CS theory on a for loop...