0

How to shift elements of an array?

Say I have to insert an element into a certain index and there will be atleast 1 null at the end. In the array {3, 10, 7, 9, null} , I have to insert ‘2’ at index 1 which is currently 10. I have to then shift 10, 7, and 9 to the right. How can I go about doing this?

12th Sep 2019, 5:11 PM
Jamie Charles
4 Respostas
+ 2
Since this is your homework, and we won't do it for you completely, you have to provide us with your attempt... Then we can guide you to solution
12th Sep 2019, 5:15 PM
Elva
Elva - avatar
+ 2
I would use a for loop which starts at the end of your array and end at the given index. for (int i = array.length - 1; i >= 1; i--){ } inside the loop: array [i] = array [i-1] array [4] = array [3] array [3] = array [2] array [2] = array [1] edit: after the loop: array [1] = 2;
12th Sep 2019, 8:50 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Use list, not array
12th Sep 2019, 8:46 PM
Marina Vasilyova
Marina Vasilyova - avatar
0
Take this as a hint.... Array has a constant size that is initialised whenever you declare an Array. So if your Array is not full then you can shift the elements otherwise you have to Declare a new array of larger size. There is no null node in array. Use Loop for shifting the elements or you can use swap if you want to insert just one element.
12th Sep 2019, 5:23 PM
Vijay Meena