0

I have this code:

static int[] a = {0 , 10 , 20, 30, 40};

public static void Main()
{
    for (int i = 0; i < 10; i++){
        int[] array = a;
        for (int j = 1; j < array.Length; j++)
            array[j] += array[j - 1];

        Console.WriteLine(array[4]);
    }
}

In the console I get the following result:

100
200
350
560
840

But I did not expect this or it is not what I want. I wanted the following result:

100
100
100
100
100

I have no idea why this is happening. How can I solve this?

Timisorean
  • 1,388
  • 7
  • 20
  • 30
  • 4
    What is the logic of the code? Why you expect 100 only in output? – Chetan Mar 01 '19 at 13:54
  • 9
    `int[] array = a` this doesn't generate a copy of the list, but points to the original list. Thus any mutation in `array` is reflected in `a`. – Caramiriel Mar 01 '19 at 13:55
  • Read this: https://stackoverflow.com/questions/1533757/is-int-a-reference-type-or-a-value-type – LeBigCat Mar 01 '19 at 13:56
  • 1
    do `int[] array = a.Clone() as int[];` – Chetan Mar 01 '19 at 13:58
  • As mentioned by others, array is referring towards original array. But if you just need to do the sum of elements of input array (a), then you do it using only int `var sum =0;` instead of `int[] array = a` and print a, – fhnaseer Mar 01 '19 at 14:26

4 Answers4

3

It seems that by doing int[] array = a you're dealing with the reference of a, so each time you modify array (in the j for loop) you're updating the a array. In the next loop the value of a will stay with the previously updated value.

Have a look at the Copy method.

fhcimolin
  • 616
  • 1
  • 8
  • 27
1

Your problem is object referance. You can try this.

 for (int i = 0; i < 10; i++)
        {
            int[] array = new int[5];

            for (int e = 0; e < array.Length; e++)
            {
                array[e] = a[e];
            }

            for (int j = 1; j < array.Length; j++)
                array[j] += array[j - 1];

            Console.WriteLine(array[4]);
        }
veliyetisgengil
  • 101
  • 2
  • 10
0

You can clone the array

static int[] a = { 0, 10, 20, 30, 40 };

public static void Main()
{
    for (int i = 0; i < 10; i++)
    {
        int[] array = (int[])a.Clone();
        for (int j = 1; j < array.Length; j++)
            array[j] += array[j-1];

        Console.WriteLine(array[4]);
    }
}
gandalf
  • 451
  • 5
  • 18
0

Use this: int[] array = a.ToArray(); instead of int[] array = a;

An array in c# is a reference type not value type like int, so when you set a into an array, a and array are same object.

DxTx
  • 3,049
  • 3
  • 23
  • 34
S.Cheginy
  • 424
  • 2
  • 15