array in c++

#include<iostream>
using namespace std;
main()
{
int i,j;
int a[4];int b[4];
for(i=0;i<=4;i++)
{
cin>>a[i];
}
for(j=0;j<=4;j++)
{
cin>>b[j];
}
for(i=0;i<=4;i++)
cout<<a[i]<<" ";
for(j=0;j<=4;j++)
cout<<b[j];
}
when i try to store elements in arr ry a[]and display them it is showing the first element(a[0]) as 0 always. I don't know why is this happening.I tried with different inputs,but no use.No issues with array b.
Arrays in C++ (and related) languages index from 0.

So if you declare
int a[4];
then your 4 elements are actually a[0], a[1], a[2], a[3].

However in you loop
for(i=0;i<=4;i++)
you are using indices i = 0, 1, 2, 3, 4. In other words, you will access an array beyond its bounds. Whatever happens then is wrong and depends on what happens to be in the adjacent memory slot.


No issues with array b

Not true. You went beyond the bounds with this array as well. It's just that positions in memory happened to let you get away with it.


Please always use code tags (first item in the format menu) for code samples. It may not work on first posting, but you can either edit your post immediately or type the tags in yourself.
Topic archived. No new replies allowed.