display and insert an element into an array

I have a problem with my c++ program. I have to insert and delete an element from an array. The two functions work if they are in two separate programs. If I put them in the same one, I get a wrong result from the delete function. Thank you.

#include<iostream.h>

int table[25],n,n1,n2,i,j,position1,position2;
void show(int table[],int n);
void addElement(int table[], int n1, int a, int position1);
void deleteElement(int table[], int n2,int position2);

void main()
{
cout<<"n=";cin>>n;
for(i=0;i<n;i++)
cin>>table[i];
show(table,n);
cout<<"Add";cin>>a;
cout<<"Position 1";cin>>position1;
n1=n;
n1++;
addElement(table,n1,a,position1);
show(table,n1);
cout<<"Position 2:";cin>>position2;
n2=n;
deleteElement(table,n2,position2);
}

void show(int table[],int n)
{
for(i=0;i<n;i++)
cout<<table[i]<<" ";
}

void addElement(int table[],int n1,int a,int position1)
{
i=n1-1;
while(i>position1) {
table[i]=table[i-1];
i--;
}

for(j=0;j<n1;j++)
if(j==position1)
table[j]=a;

}

void deleteElement(int table[],int n2,int position2)
{
for(i=position2;i<n2-1;i++) table[i]=table[i+1];
n2--;
for(j=0;j<n2;j++)
cout<<table[j]<<" ";
}
There are many problems with this code. First of all, the global variables which are partly hidden by parameter names in functions etc. All this leads to that you don't really understand who is the owner of the variables and at which places they should be modified. The error in this case is a double decrement of n2 (btw, use code <> button for code - in formatting box on the right). It is decremented before deleteElement and inside deleteElement. What you should do is make all the variables local, and let the add and delete functions modify the length of array - i.e. pass n by reference:
1
2
void addElement(int table[], int& n, int newElement, int addPosition)
void deleteElement(int table[],int& n, int deletePosition)
.
In your case you should also try to avoid all these duplications like "n, n1, n2, position1., position2" - it is easy to get lost in what these values mean and you dont really need them. Or give them more meaningful names.
Topic archived. No new replies allowed.