phil_a11
phil_a11

Reputation: 63

Looping through a large array and adding the values together C#

I'm trying to loop through an array of 180 elements and add the first 60 elements together and store it in a list. Then add the next 60 elements together and store them in the list and repeat that for the final 60. So far my code will only add the first 60 and store them in the list. the problem seems to be the "i % 60 == 0" in the else if statement but I'm not sure why

Random r = new Random();
        
        int[] arr = new int[180];
        List<int> MyList = new List<int>();
        int[] array2 = new int[2];

        //intialize random numbers in 60 length array
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = r.Next(1, 10);
        }

 int score = 0;
        //looping through arr
        for (int i = 0; i < arr.Length; i++)
        {
            
            if (i % 60 != 0 || i == 0 )
            {                
                score = score + arr[i];
                
                i++;
            }
            else if (i % 60 == 0 && i != 0)
            {
                //adding the values to a list
                MyList.Add(score);
                //resetting score after score is added to the list
                score = 0;
            }
            
        }
        // converting list to my second array
        array2 = MyList.ToArray();

        //printing values in array
        for (int i = 0; i < array2.Length; i++)
        {
            Console.WriteLine(array2[i]);
        }

Upvotes: 0

Views: 304

Answers (1)

Dusan
Dusan

Reputation: 5144

Your original loop and conditions have several problems and actually need to be:

int score = 0;
for (int i = 0; i < arr.Length; i++)
{
    score = score + arr[i];

    if ((i + 1) % 60 == 0)
    {
        MyList.Add(score);
        score = 0;
    }
}

But I strongly advise you to use much simpler LINQ approach (instead of doing all the stuff manually):

var array2 = new[] 
{
    arr.Take(60).Sum(),
    arr.Skip(60).Take(60).Sum(),
    arr.Skip(120).Sum()
};

Upvotes: 2

Related Questions