array in c++

when run the following code.
#include <iostream>
using namespace std;
int main()
{
int sample[5]{}; //this reserved 10 integer elment
int t;
// Load the array

for (t = 0; t < 10; ++t) sample[t]=t;
for (t = 0; t < 10; ++t);
cout << "this is sample [<< t << ]: " << '\n'<< sample[t] ;
return 0;
}

the result should be "0123456789" but instead it give me different value every time .
compiled in visual studio CMD in a 64 bit w10.
Please can you help me .
Why do you think the following line gives you 10 elements?
 
int sample[5]{}; //this reserved 10 integer elment 

I see only 5 elements.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
int sample[5]{}; //this reserved 10 integer elment
Your comment lies to you. That only allocated 5 ints, not 10. Notice the 5.

sample[5], sample[6], sample[7], sample[8], and sample[9] don't exist, so your for loop is going out of bounds, which invokes undefined behavior.
Topic archived. No new replies allowed.