I made a code in which I had to take the size of an array as the user’s input and its elements too and print them.
#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
int main()
{
int i;
cout<<"\nenter the size of array";
cin>>i;
int n[i];
for(int j=0;j<=i;j++)
{
cout<<"\nn["<<j<<"]=";
cin>>n[j];
}
for(int k=0;k<=i;k++)
{
cout<<endl;
cout<<"\nn["<<k<<"]=";
cout<<n[k];
}
}
Suppose in the following:
The value of i
is 3 (according to user’s input).
In the first loop the condition for j
is up to <=i
where i is the size of array (this shouldn't happen as i
begins from 0) due to which the Compiler asks me to input 4 values for the array (n[0]
, n[1]
, n[2]
and n[3]
) but the size of the array is 3 only. How can it store 4 objects?