array

Hi there,

I need to assign for each element of an array by for loop but how can I do that?

for example

int X[5]

for (i=1; i=5; ++i)
X[]=i
1
2
3
int x[5];
for(int i=0;i<5;i++)
     cin>>x[i];



x[0] indicates to the first element of the list so we have to initialize i with 0
x[1] indicates to 2nd element of the list
and so on

you have to read first about arrays and loops

http://www.cplusplus.com/doc/tutorial/arrays/
http://www.cplusplus.com/doc/tutorial/control/

Last edited on
int X[5]; // Dont forget semicolon, I added it here.

When you create an array of the size 5, or any size, it alway starts at 0. So an array of the size 5 goes from 0-4.

Meaning, if you want to fill the array or use it. You will have to use a for loop that runs 5 times, starting at 0 and ending at 4.

1
2
3
4
for(int i = 0; i < 5; i++)
{
     // Here is were you work with your array.
}
Last edited on
thanks but I should explain my question better

int X[5];

for(i=3; i<8; ++i){
X[]=i;
}

I mean I need like this:
X[0]=3
X[1]=4
X[2]=5
X[3]=6
X[4]=7

Last edited on
You just need to put the index into the assignment statement. Some quick math shows that the index is i-3:
1
2
3
4
5
int X[5];

for(i=3; i<8; ++i){
    X[i-3]=i;
}


It's much more common for the loop variable to be the index of the array, so I'd flip this around like so:
1
2
3
4
5
int X[5];

for(i=0; i<5; ++i){
    X[i]=i+3;
}

Topic archived. No new replies allowed.