array + programming C++?

2009-09-13 8:11 pm
include <stdio.h>
int main ( )
{
int i, list1[10] = {0, 1, 2, 3, 4, 5 , 6 , 7, 8, 9};
int list2[10];

for (i = 0; i < 10; i ++)
list2[i] = list1[9 – i];
for (i = 0; i < 10; i++)
printf(“%d %d\n”, list1[i], list2[i]);
return 0;
}

The answer i get is 09 18 27 36 45 54 63 72 81 90.
may i know why?? anyone can explain it to me?? I don't really know it's concept.

Thanks.

回答 (2)

2009-09-13 8:36 pm
✔ 最佳答案
First, you set up an array called list1, which has ten elements. Then you set the value of the elements as the integers 0 through 9.

Next you define a new array of ten elements called list2. But we don't set the value of this array yet.

Now you use a for loop. You use the counter i to make the loop run through 10 iterations. Here is what the loop does:

First Iteration: i = 0. The first element of list2 (list2[i] = list2[0]) is set to 9 - i, which is 9 - 0, or 9. Now you add 1 to i. Now we print the first element of list1 (0) and the first element of list2 (9) together as a pair, and then tell it to drop to a new line on the console.

Second iteration: i = 1. The second element of list2 is set to 9 - i, which is 9 - 1, or 8. Now you add 1 to i. We print the pair again, and get list1[1] = 1 and list2[1] = 8, thus 18.

Third iteration: i = 2, etc.
2009-09-13 8:31 pm
well your code is storing numbers into one array as 0 through to 10.

Your first for loop will store the numbers from the first array into the second array in reverse order. That means that the first item in the list2 array will be the last item in the list1 array until the last item in list2 is the same as the first item in the list1 array.

The second for loop will print both the arrays out in index order. So thats why the answer is what you get.

Hope this helps?


收錄日期: 2021-04-24 23:10:41
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090913121158AAirGED

檢視 Wayback Machine 備份