[英]Hand execution in c, don't understand what index -1 means
I have this code and I am trying to do a hand execution from it but I am not sure what index - 1
does.我有这段代码,我正在尝试从中手动执行,但我不确定
index - 1
是做什么的。 Should my result be 1,5,6,8,9
or 1,3,5,6,8
or am I completely wrong?我的结果应该是
1,5,6,8,9
还是1,3,5,6,8
还是我完全错了?
void main() {
int array[5] = {1,3,4,6,7};
int index;
for (index = 1; index < 5; index++) {
array[index] = array[index - 1] + 2;
}
}
values in array before start loop: 1,3,4,6,7开始循环前数组中的值:1,3,4,6,7
The value for index is set at the top of each iteration of the for loop. index 的值设置在 for 循环每次迭代的顶部。
So the first time through the loop, index
is set to represent the value 1
.所以第一次通过循环时,
index
被设置为表示值1
。
index-1
would hold the value 1-1
, or 0
index-1
将保存值1-1
,或0
array[index - 1]
is the same as array[0]
array[index - 1]
与array[0]
相同array[0]
holds the value 1
. array[0]
保存值1
。array[index - 1] + 2
is the same as 1 + 2
, or 3
array[index - 1] + 2
与1 + 2
或3
array[index]
which we know to represent the array[1]
which used to hold the value of 3
, now is assigned to (again) hold the value 3
.array[index]
,我们知道它代表array[1]
,它曾经保存3
的值,现在分配给(再次)保存值3
。 values in array at end of 1st time through the loop: 1,3,4,6,7第一次循环结束时数组中的值:1,3,4,6,7
Now, back up to the top of the loop.. index
is told to increment itself by 1
现在,回到循环的顶部..
index
被告知将自身增加1
ie: index
which was 1 , now represents the number 2
即:
index
为 1 ,现在表示数字2
index-1
would hold the value 2-1
, or 1
.index-1
将保存值2-1
或1
。array[index - 1]
is the same as array[1]
,array[index - 1]
与array[1]
相同,array[1]
holds the value 3
array[1]
保存值3
array[index - 1]
+ 2, is the equivalent of 3 + 2
, or 5
array[index - 1]
+ 2,相当于3 + 2
,或者5
array[index]
which we know to represent the element array[2]
( which used to hold the value of 4
) , now is assigned to hold the value 5
.array[index]
,我们知道它代表元素array[2]
(它曾经保存4
的值) ,现在分配给保存值5
。 values in array at end of 2nd time through the loop: 1,3,5,6,7第二次循环结束时数组中的值:1,3,5,6,7
etc.等等。
array index index-1 array[index-1] array[index-1]+2 array[index]
1,3,4,6,7 1 0 1 3 array[1] = 3
1,3,4,6,7 2 1 3 5 array[2] = 5
1,3,5,6,7 3 2 5 7 array[3] = 7
1,3,5,7,7 4 3 7 9 array[4] = 9
1,3,5,7,9 5 (exits for loop since condition fails)
final result: 1 3 5 7 9
最终结果:
1 3 5 7 9
Also, you can use an 'online c compiler' to test code snippets.
此外,您可以使用“在线 c 编译器”来测试代码片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.