Explanation of the following nested for loop: 以下是对以下嵌套循环的解释:

huangapple go评论75阅读模式
英文:

Explanation of the following nested for loop

问题

I need an explanation for the following nested for loop:

public static void main(String[] args) {
	int x = 0;
	int y = 30;

	for (int outer = 0; outer < 3; outer++) {
		for (int inner = 4; inner > 1; inner--) {
			x = x + 3; // 3
			y = y - 2; // 28
			if (x == 6) {
				break;
			}
			x = x + 3; // 6
		}
		y = y - 2; // 26
	}

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

The output is 54 6, but I am confused how this is the answer. I've tried going through this myself, and I've found that the for loop for 'inner' results in 4 3 2 4 3 2 4 3 2. The 'outer' for loop results in 0 0 0 1 1 1 2 2 2.
How do x and y play into this and get these values? Thank you so much!

英文:

I need an explanation for the following nested for loop:

public static void main(String[] args) {
	int x = 0;
	int y = 30;

	for (int outer = 0; outer &lt; 3; outer++) {
		for (int inner = 4; inner &gt; 1; inner--) {
			x = x + 3; // 3
			y = y - 2; // 28
			if (x == 6) {
				break;
			}
			x = x + 3; // 6
		}
		y = y - 2; // 26
	}

	System.out.println(x + &quot; &quot; + y);
}

The output is 54 6, but I am confused how this is the answer. I've tried going through this myself, and I've found that the for loop for 'inner' results in 4 3 2 4 3 2 4 3 2. The 'outer' for loop results in 0 0 0 1 1 1 2 2 2.
How do x and y play into this and get these values? Thank you so much!

答案1

得分: 1

I will only provide translations for the text you provided without any additional content. Here it is:

你可能会将循环索引,外部和内部,与 x 和 y 搞混,但它们是不同的变量。

外部循环执行3次,内部循环执行9次(每次外部循环迭代3次)。
因此,它们都会完全执行,因为永远不会进入可能中断循环的 if 语句。

x 在内部循环中只增加了3两次,所以它将达到(3+3)*9 = 54的值。

y 在内部循环中将减小2 9次,在外部循环中减小3次。所以它将是30 - (2 * 9) - (2*3) = 6。

循环示例

outer=0
inner=4
   x=3
   Y=28
   x=6
inner=3
   x=9
   y=26
   x=12
inner=2
   x=15
   y=24
   x=18
内部循环结束
y=22
outer=1
inner=4
....
依此类推
英文:

You probably confuse the loop indices, outer and inner, with x and y, but they are different variables.

The outer loop is executed 3 times, the inner loop 9 times ((3 times for each iteration of the outer loop).
So both are executed completely, because the if which could break the loop is never entered.

x, which is increased of 3 twice in the inner loop only, will reach the value of (3+3)*9 = 54

y will be decreased of 2 9 times in the inner loop and 3 times in the outer loop. So it will be 30 - (2 * 9) - (2*3) = 6

Loop samples

outer=0
 inner=4
   x=3
   Y=28
   x=6
 inner=3
   x=9
   y=26
   x=12
 inner=2
   x=15
   y=24
   x=18
 end of inner loop
 y=22
 outer=1
  inner=4
 ....
 and so on

huangapple
  • 本文由 发表于 2020年8月13日 14:00:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63389012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定