-2

Here is my code

public static int[] MoveZeroes(int[] arr)
    {
        // TODO: Program me
        int zeroCount = 0;
        int[] temp = { };
        int numberItems = 0;
        foreach (var a in arr)
        {

            if (a == 0)
            {
                zeroCount += 1;
            }
            else
            {
                temp[numberItems] = a;
            }

            numberItems += 1;

        }
        return new int[] { };
    }

i use it like

   int[] f = MoveZeroes(new int[] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0});

But this is giving me error Index was outside the bounds of the array on line

temp[numberItems] = a;

how can i add items in array? what am i doing wrong ?

James
  • 1,827
  • 5
  • 39
  • 69
  • 3
    You can't dynamically resize an array. I'd recommend using a `List` instead of an array for your `temp` variable. I don't really understand what your method is supposed to do though. It looks like you're just trying to make an array composed of all the 0s in the array you pass in. But then you just throw everything away and return an empty array at the end without actually changing the source array. – itsme86 Aug 15 '19 at 14:50
  • Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Ňɏssa Pøngjǣrdenlarp Aug 15 '19 at 14:53

1 Answers1

1

int[] temp = { }

This creates an array of ints that is 0 elements long. You can't insert into it because it has 0 length.

Use a List<int> and you can dynamically add to it:

public static int[] MoveZeroes(int[] arr)
{
    // TODO: Program me
    int zeroCount = 0;
    var temp = new List<int>();
    int numberItems = 0;
    foreach (var a in arr)
    {

        if (a == 0)
        {
            zeroCount += 1;
        }
        else
        {
            temp.Add(a);
        }

        numberItems += 1;

    }
    return temp.ToArray();
}
Neil
  • 11,059
  • 3
  • 31
  • 56