Weird issue with range based for loop

I am working on learning vectors in my C++ object oriented 1 class and we have been introduced the concept of range based for loops. I decided to practice the range based for-loops separately so that I could get used to the syntax but I came across a weird issue.

#include<iostream>
 using namespace std;
 int main()
 {
   int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
   for ( auto i: a)
     {
       cout << a[i] << " ";
     }

 return 0;
 }

When I run the above code my output is the following.

2 3 4 5 6 7 8 9 0 1 Press any key to continue...

My output should read

1 2 3 4 5 6 7 8 9 0 Press any key to continue...

Can anyone tell me why my first index is skipped? I have visual studio 2013 professional.

You get the weird output becauseiin the range loop is the value from the array, not an index. That is,

for (auto i : a)

loops throughvaluesofa. In your code you're effectively printing the sequencea[a[0]],a[a[1]], etc.

The code you probably want is

for (auto i : a) {
    std::cout << i << std::endl;
}
What Others Are Reading