array... pls help ...?

2009-09-14 6:51 am
include <stdio.h>
int main ( )
{
int i, list[10] = {0};

for (i = 0; i < 5; i ++)
list[2 * i + 1] = i + 3;
for (i = 0; i < 10; i++)
printf(“%d\n”, list[i]);
return 0;
}

I know the answer is 0 3 0 4 0 5 0 6 0 7

but how do we get this? can tell me???
更新1:

to sushil c : erm.. may i know why elements in vector with even index wont change and it still be 0? Thanks a lot.. =)

回答 (2)

2009-09-14 7:07 am
✔ 最佳答案
list[10]={0} ==> null vector i.e all elements of vector list are zero

==>
list[0]=0
list[1]=0
.
.
.
list[9]=0

now 1st for loop will run 5 times... i=0 to 4
elements in vector(1D array) "list" with odd index= i+3 (where i=0 to 4)

i.e.
list[1]=0+3=3 where i=0 and 2*i+1=1
list[3]=1+3=4 where i=1 and 2*i+1=3
.
.
a[9]=4+3=7 where i=4 and 2*i+1=9

but elements in vector with even index wont change...that is those values are still zero...
using 2nd for loop you are printing all 10 elements of 1D array
there for output will be
0
3
0
4
0
5
0
6
0
7

EDIT:
@peggy
because in 1st 'for' loop
index=2*i+1 which is always odd for any integer i
so even indexed elements wont change..

@AnalProgrammer
1xn or nx1 matrix is called a vector...
yea you are right I should call it 1D array in programming.
2009-09-14 4:24 pm
In computing this is an array, not a vector. A vector is a special type of array.

list[2 * i + 1] = i + 3;
Because of this calculation [2 * i + 1] the program cannot reach the even indexes of the array.

i = 0 - 2 * i (0) + 1 = 1
i = 1 - 2 * i (2) + 1 = 3
etc.

Have fun.


收錄日期: 2021-04-25 13:28:31
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090913225116AAVGF0T

檢視 Wayback Machine 備份