0

How can I add a single Integer to an Integer Array?

 if (valuesHigherThanAverage.Length == 0) valuesHigherThanAverage[valuesHigherThanAverage.Length] = arrayGetal;
 else valuesHigherThanAverage[valuesHigherThanAverage.Length + 1] = arrayGetal;

I have this code and I have also tried with for or foreach loop but it doesn't worked. And I need to use an INT[] and may not use an List.

6
  • 2
    Arrays have a fixed size. Commented Dec 1, 2017 at 8:47
  • If you cannot use List<> then create new array which is 1 element bigger, assign old array and assign new value to the last element. Commented Dec 1, 2017 at 8:48
  • See ArrayList class. It can easily be transformed to normal array when necessary. Commented Dec 1, 2017 at 8:48
  • 1
    What, pray tell, is wrong with a list? Commented Dec 1, 2017 at 8:49
  • 1
    if (valuesHigherThanAverage.Length == 0) that means that the array has NO element, which also means that you cannot access the element at position 0! Generally this: valuesHigherThanAverage[valuesHigherThanAverage.Length] will always lead to an IndexOutOfBounds exception. Because Length is always 1 number larger than the maximum index you can use. Indexing starts at 0 and counting at 1 Commented Dec 1, 2017 at 8:50

4 Answers 4

3

You can't add a new item in an array, you have to create a new array with size+1, copy all existing values, and then set the last item value.

An easier way is to use a List<int>, which will automatically resize if you run out of space. Calling the Add method suffices then.

Here a sample of an array resizing algorithm (Array.Resize could automate this, but this is just to show you how it should work):

int[] oldItems = new int[] { 1, 2, 3 };

int[] newItems = new int[oldItems.Length * 2];

for (int i = 0; i < oldItems.Length; i++)
{
    newItems[i] = oldItems[i];
}

newItems[oldItems.Length + 1] = 4;
Sign up to request clarification or add additional context in comments.

2 Comments

I'd recommend to increase the size not only by 1 but a little more. The exact number may be "inspired" by List implementation?
Indeed, I would use *2.
0

The array is not designed to be extended as new elements are added. You will need to call Array.Resize(Of T) to increase the size but this is will be quite inefficient.

Data types more in line for what you want to do is List<T>.

Comments

0

You cannot change the size of array like valuesHigherThanAverage.Length + 1. It has fixed size. You are crossing the upper bound of the array.

Comments

0

You can create a new Array with the length of the old array + 1.

public static int[] AddIntToArray(int[] sourceArray, int addValue)
{
    int[] newArray = new int[sourceArray.Length + 1];
    Array.Copy(sourceArray, newArray, sourceArray.Length);
    newArray[newArray.Length] = addValue;
    return newArray;
}

Comments