### Facing difficulties in shifting & insert new numbers in array

The question says
 Write a function named insertNewElement that takes four parameters: an array of integers (List), an integer (newItem), the number of elements in the array (Length), and the maximum size of the array (Max_Size). Assume that the elements in the array are sorted in ascending order. The function should add newItem in a way that the element in the array will remain sorted. Note that the Length of the array should not exceed Max_Size, i.e. if List is full, then the insertion is not performed and an appropriate message is displayed.

My solution but it's wrong
 1234567891011121314151617181920212223242526272829 void insertNewElement(int List[], int newItem, int &length, const int Max_Size) { int index=0; if(length == Max_Size) cout<<"Cannot add a new item as the array is full"< newItem) { index=i; for(int x=length; x>index; x--) { List[x+1]=List[x]; } List[index]=newItem; length++; } } cout<<"The numbers of the array is:\n"; for(int j=0; j<=length; j++) { cout<

Can anybody tell me where is my error exactly, and what should I do?
It is obvious that this loop is invalid

 123456789101112131415 for(int i=0; i newItem) { index=i; for(int x=length; x>index; x--) { List[x+1]=List[x]; } List[index]=newItem; length++; } }

You shall not insert the new element inside the loop and change the length of the array.
Last edited on
Thanks you, I got it working so far but I don't know weather it is 100% right or still missing things?
 1234567891011121314151617181920212223 void insertNewElement(int List[], int newItem, int &length, const int Max_Size) { int index; if(length == Max_Size) cout<<"Cannot add a new item as the array is full"<newItem) break; for(int i=length; i>index; i--) List[i]=List[i-1]; List[index]=newItem; length++; cout<<"The numbers of the array is:\n"; for(int j=0; j
Topic archived. No new replies allowed.