Why I am getting wrong output? Suppose, If I am initializing 10 as array initial size and then 15 more elements to append at the end of an array. Then array total size will be 25. But in below code when I input multiple values to append at the end of array then after some input values either program stop or give wrong output.
Help Please !! Is Something wrong with my code?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,elem,lastindex=0;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cout<<"enter index "<<i<<" value number is "<<i+1<<": ";
cin>>arr[i];
lastindex++;
}
cout<<"lastindex current value: "<<lastindex<<endl;
cout<<"How many elements you want to add at the end of the element: ";
cin>>elem;
elem = lastindex + elem;
cout<<"elem now: "<<elem<<endl;
for(int i=lastindex; i<elem; i++)
{
cout<<"enter index "<<lastindex<<" value number is "<<lastindex+1<<": ";
cin>>arr[i];
arr[lastindex] = arr[i];
lastindex++;
cout<<"i: "<<i<<endl;
cout<<"lastindex: "<<lastindex<<endl;
cout<<"elem: "<<elem<<endl<<endl;
}
cout<<"last index current value: "<<lastindex<<endl;
// arr[lastindex] = elem;
for(int i=0; i<lastindex; i++){
cout<<arr[i]<<" ";
}
}