Why the -1 in this for loop

Why in the bottom for loop is it "index = numbers_used - 1;..."
index was initialized to 0 and then numbers_used was set to index. If index started at one I would get it. Is it because if I input: " a b c ." I have filled a[0,1,2,3] ??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
using namespace std;

const int MAX = 10;

int main()
{
    char a[MAX], next;
    int index = 0;

    cout << "Please enter in up to 10 letters ending with a period: " << endl;
    cin >> next;

    while((next != '.') && (index < 10))
    {
        a[index] = next;
        index++;
        cin >> next;
        //cout << " " << next << endl;
    }

    for(index = numbers_used -1; index >= 0; index--)
        cout<<a[index];
    cout << endl;
I don't see where numbers_used is even defined. But my guess is at that point numbers_used is equal to the size of the array, which is not a valid index (points one past the last element). So this code uses numbers_used - 1 to point to the last element in the array, and then iterate backwards through that array.
index gets incremented in the while loop to one element past the last one written into the array, so if numbers_used gets set to index after the while loop, you'd need to go back one element to get to the first element you want to output.
Last edited on
biscuit it was a cut and paste misfire. I changed the code and added a cout after it to see what numbers_used was using input ' a b c . ' It came out to three not the expected four??? Now if I subtract the one I get 2. 0 - 2 is three cycles so everything is okay but why not the four?
nevermind it only increments after checking for the period
Topic archived. No new replies allowed.