0

Hi guys I got a small problem for some reason I got an error on my sum. and however and where ever I put my int sum; it wont fix the error.

static void TotalOfEvenNegatives(int[] array)
{
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] % 2 == 0 && array[i] < 0)
        {
            int sum;
            sum += array[i];
        }
    }
}
2
  • 4
    you should probably return the sum too Commented Mar 4, 2014 at 18:29
  • 1
    How about return array.Where(x => x % 2 == 0 && x < 0).Sum(); ? Commented Mar 4, 2014 at 18:36

3 Answers 3

2
static void TotalOfEvenNegatives(int[] array)
{
    int sum = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] % 2 == 0 && array[i] < 0)
        {

            sum += array[i];
        }
    }
}

You need to initialise it outside the loop and set it to 0. By setting it inside the loop, you are overriding it every iteration so it can never increment.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I had to set it to 0 I didn't think of that.
1

You are declaring sum inside your loop, thus overwriting all the values, declare it outside.

static int TotalOfEvenNegatives(int[] array)
{
    int sum = 0; //HERE

    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] % 2 == 0 && array[i] < 0)
        {
            sum += array[i];
        }
    }
    return sum;
}

Also your method should return sum and you can use it like:

int total = TotalOfEvenNegatives(new [] {1,2,3,4,}; //ClassName.TotalOfEvenNegatives

Do not forget to initialize the sum with 0 otherwise you will get the error "Use of unassigned variable"

2 Comments

I did try to declare it outside but it still gives me the same problem.
@TheBoringGuy, assign it 0 at the time of declaration, otherwise you will end up with error "Use of unassigned variable"
0

Why not do it the simple way:

      int[] myArray = {1,2,3,4,} ;
      int   sum     = myArray.Where( x => x < 0 && 0 == x % 2 ).Sum() ;

1 Comment

its nice but I don't like to use something I haven't learned yet :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.