Trying to teach myself c++, just wondering how to populate array with for loop.
Aug 9, 2016 at 3:21pm UTC
Having trouble populating array with for loop. To me everything seems logically correct but the compiler says otherwise with I try print the contents of the array on screen, It shows up with -848993460. Can someone tell me why this happened and what I'm doing wrong.
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
#include <iostream>
using namespace std;
{
int array[4];
int i = 0;
cout << "Enter 4 numbers " ;
for (i; i < 4; i++)
{
cin >> array[i];
}
cout << array[i];
return 0;
}
Aug 9, 2016 at 3:30pm UTC
Your last cout is accessing the array out of bounds, i is equal to 4 after that loop. I'd recommend something more like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
using namespace std;
int main()
{
int array[4];
cout << "Enter 4 numbers " ;
for (auto & itr : array)
cin >> itr;
for (auto & itr : array)
cout << itr << " " ;
cout << endl;
return 0;
}
Aug 9, 2016 at 3:38pm UTC
thanks very much, I've never seen something like for (auto & itr : array)
before, Can you briefly explain whats going on there?
Aug 9, 2016 at 3:44pm UTC
> Thanks very much, I've never seen something like "for(auto& itr : array)"
It is actually a range-based for-loop.
Learn more :
http://en.cppreference.com/w/cpp/language/range-for
Topic archived. No new replies allowed.