简体   繁体   中英

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. Should my result be 1,5,6,8,9 or 1,3,5,6,8 or am I completely wrong?

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

The value for index is set at the top of each iteration of the for loop.
So the first time through the loop, index is set to represent the value 1 .

  • so index-1 would hold the value 1-1 , or 0
  • so array[index - 1] is the same as array[0]
  • array[0] holds the value 1 .
  • hence array[index - 1] + 2 is the same as 1 + 2 , or 3
  • So then, we assign 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 .

values in array at end of 1st time through the loop: 1,3,4,6,7

Now, back up to the top of the loop.. index is told to increment itself by 1
ie: index which was 1 , now represents the number 2

  • so index-1 would hold the value 2-1 , or 1 .
  • so array[index - 1] is the same as array[1] ,
  • array[1] holds the value 3
  • so array[index - 1] + 2, is the equivalent of 3 + 2 , or 5
  • So then, we assign 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 .

values in array at end of 2nd time through the loop: 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

Also, you can use an 'online c compiler' to test code snippets.

Here's one: JDoodle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM