Variable attachment?

Why is it that sometimes in for loops there are two variables stuck together, kind of like variable[i]?

1
2
3
4
5
for (int i = 1; i <= 10; ++i)
{
    cout << "Variable " << i;
    cin >> variable[i];
}


It looks like i is being attached to the variable, but how does that work? Does the variable adopt the value of i?
That is the syntax for accessing array elements.

See: http://www.cplusplus.com/doc/tutorial/arrays/
Thank you. I have read that article, and while I do (mostly) understand the concept of arrays, I still don't understand how the control variable, such as i, in a loop can seemingly attach itself to another variable.

Okay, before wasting any more of anyone's time, let me express my muddled thoughts as to why I think this might be the case.

A variable is initialized as an array. The parameters must be empty of elements, but given a total size, such as int variable [5].

When the for loop is run, depending on what conditions are present, the aforementioned variable (with the empty elements), is attached to the control variable, such as i, so that the empty elements are filled with the values of the control variables increment values.

Is that how it works? Is i attached to a variable with empty elements so that the variable can have the value of i?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
int ar[5]; /* <- creates an array of 5 elements.

Each element is its own int... so this is like creating 5 separate variables:

  ar[0]
  ar[1]
  ar[2]
  ar[3]
  ar[4]
*/

ar[0] = 3; // <- assign 3 to one of the ints in our array...
           //      .. ar[0].  It's ar[0] because the number 0 is
           //      in the brackets
           
int index = 3;
ar[index] = 2;  // <- assigns 2 to one of the ints in our array.
                //   Which int?  Well since the value in the brackets
                //   is 'index', the contents of 'index' is used to
                //   determine which element.  Since index==3, this
                //   means we are assigning ar[3]
    
/*  This will create a loop with a counter 'i' that starts at 0.
    Each time the loop completes, 'i' will be incremented.
    Once i is no longer <5, the loop stops
*/    
for(int i = 0; i < 5; ++i)
{
    ar[i] = i;  // <- what does this do?
}

/*
    The first time the loop runs... i==0
    so the line in question will assign ar[0]=0
    
    The next time the loop runs... i==1
    so the line will assign ar[1]=1
    
    and so on... and so on.  Ultimately you are left with:
    
    ar[0]=0
    ar[1]=1
    ar[2]=2
    ar[3]=3
    ar[4]=4

    At which point the loop will stop, because i will be 5... which makes i<5 false, which
    ends the loop.
*/
Last edited on
Oh, I see! It's just like adding new integers to an already established list of integers. That makes things so much clearer. Thank you very much Disch!
Topic archived. No new replies allowed.