I am trying to insert a value "item" in a sorted linear array at position "pos" when i take input in the array using a initialization list the code works fine .. however when i take input using a for loop the code does not work
#include<iostream>
using namespace std;
int main()
{
const int size = 10;
int num[size];
int num[size] = {1,2,3,4,5,6,7,8,9,10}; //a sorted linear array
int item;
int pos;
int i;
/*
for(int a=0;a<size;a++)
{
cin>>num[a];
}
*/
cout<<"Enter item"<<endl; //insert this item in array
cin>>item;
cout<<"Enter Position To Insert"<<endl;
cin>>pos;
i=size-1;
while(i>=pos)
{
num[i+1]=num[i];
i=i-1;
}
num[i+1] = item;
cout<<endl;
cout<<"array after insertion"<<endl;
for(int b=0;b<size;b++)
{
cout<<num[b]<<endl;
}
system("pause");
return 0;
}
the for loop causing the problem
for(int a=0;a<size;a++)
{
cin>>num[a];
}
This code snippet
i=size-1;
while(i>=pos)
{
num[i+1]=num[i];
i=i-1;
}
num[i+1] = item;
is wrong. First of all pos
can be greater than or equal to size
In this case none element should be inserted in the array. However according to the last statement of the code snippet
num[i+1] = item;
num[size]
will be asssigned with item
.
Again within the loop for initial value of i equal to size - 1
there is an attempt to assign num[size]
element
num[i+1]=num[i];
The code snippet can be rewritten for example the following way
if ( pos < size )
{
i = size;
while ( --i != pos ) num[i] = num[i-1];
num[i] = item;
}