0

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;
}
0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

can you tell me the way you approach?i mean i want to get the concept of shifting
@MobinaK: I don't understand what exactly you mean by shifting here, but what I did in my answer was to move each index of the array backward by one position. This means that if you keep repeating this by the length of the array - 1, then all indexes will be set to zero expect the first one.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.