I was working through one of the examples in my book on C++ with dealing with while loops. I understand the concept of the while loops, however I don't get the example, I also understand vector arrays, which were taught earlier.
The code is
The output is " | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10" as it shows in the book. However I don't understand the one part where you get the array of vec[i-1] (which would be equal to zero. Then it outputs the element at "i - 1" in the array, but that would equal -1, and not 1. I simply do not understand how that output was created. Even though it turns out right. Shouldn't it be in the negatives instead?
Edit: I tried going through it step by step, and I just get stuck, the value of i goes into the negatives, so shouldn't the output be in positives and not negatives. I just have no idea what to do. It makes absolutely no sense to me.
Thanks.
John
The code is
Code:
#include <vector>
#include <iostream>
using namespace std ;
// A C++ application demonstrating the while loop
int main()
{
vector <int> vec( 10 ) ;
int i = 0 ;
while ( i < vec.size() )
{
i++ ;
vec[ i-1 ] = i ;
cout << " | " << vec.at( i - 1 ) ;
}
return 0;
}
The output is " | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10" as it shows in the book. However I don't understand the one part where you get the array of vec[i-1] (which would be equal to zero. Then it outputs the element at "i - 1" in the array, but that would equal -1, and not 1. I simply do not understand how that output was created. Even though it turns out right. Shouldn't it be in the negatives instead?
Edit: I tried going through it step by step, and I just get stuck, the value of i goes into the negatives, so shouldn't the output be in positives and not negatives. I just have no idea what to do. It makes absolutely no sense to me.
Thanks.
John