I want to Inset element in array

I am using a sample program to insert element in array and it work all the way to the number to insert and locks up. Help please. I am using CodeBlocks to compile.
//C++ insert Element in Array: Program Example :
#include<iostream>
#include<stdlib.h>
#include<conio.h>
using namespace std;

int main()
{
int i,a[5],no,pos;
system("cls");
cout<< "Enter data in Array: ";
for(i=0;i<5;i++)
{
cin>>a[i];
}
cout<< "\n\nStored Data in Array: ";
for(i=0;i<5;i++)
{
cout<<a[i];
}
cout<< "\n\nEnter position to insert number: ";
cin>>pos;
if(pos>5)
{
cout<< "\n\nThis is out of range";
}
else
{
cout<< "\n\nEnter New Number: ";
cin>>no;
--pos;
for(i=5;i>=pos;i--)
{
a[i+1]=a[i];
a[pos]=no;
}
cout<< "\n\nNew Data in Array: ";
for(i=0;i<6;i++)
{
cout<<a[i];
}
}
getch();
}
Last edited on
1
2
for(i=5;i>=pos;i--)
a[i+1]=a[i];
In the first 2 for loops you knew that max array index is 4. Then you had a kind of amnesia and accessed array elements that don't exist.
Topic archived. No new replies allowed.