• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

CS theory on a for loop...

 
marque hudspeth
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marque hudspeth
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ty, Jess. That was a swift and informative reply. Thank you very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic