I'm trying to figure out how to add an element to an array of integers, but the tricky part is that I have to slide the elements to the right of it over by one place.

For example:

Start array: {1, 2, 3, 4, 5, 6, 7}
Adding 10 to index of 3
End result: {1, 2, 3, 10, 4, 5, 6, 7}

This what I have so far. Thanks so much.

//slide all elements over
			for(int i=index; i<values; i++){
				int holder=array[i];//holds value that is going to be replaced
				//are overriding values in i+1, need to save
				array[i+1]=holder;	
			}
			array[index]=element;

Recommended Answers

All 3 Replies

Write down your replacement progression through the loop on paper. I believe you'll see that you are holding the wrong value if you loop proceeds in a positive direction.

Of course, you don't necessarily have to loop in a positive direction either.

Ya I see that I'm overriding the next value before it can be replaced but I don't understand how I can hold the value before replacing it. :/

If you can hold one element, you can just as easily hold the next. Which value do you need to keep from overwriting? Hold that one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.