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);
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.