Reputation:
I have an array and I want to shift its element to left without any helper array... how can I do this? I tried to do this but I think it's not the best way... a1 is an array that I want to shift its element
for (int i = 0; i < a1.Length ; i++)
{
foreach (var element in a1)
{
current = element;
next = a1[i];
next = current;
}
current = a1[i];
next = a1[i + 1];
a1[i] = next;
}
Upvotes: 0
Views: 78
Reputation: 555
It may help:
//say you have array a1
var first_element = a1[0];
//now you can shift element_2 to position_1 without fear of
//loosing first_element
for(int i=0;i<a1.Length-1;i++)
{
a1[i] = a1[i+1];
}
//shift first_element to last place.
a1[a1.Length-1] = first_element;
Upvotes: 1
Reputation: 5755
If by shifting to the left, you mean shifting to the top, then this would be a solution:
for(int i = 1; i < array.Length; i++){
array[i-1] = array[i];
}
array[array.Length-1] = 0; // default value
Upvotes: 1