Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array adding odd values

Tags:

arrays

c#

math

I have a small problem: I got all the odd numbers to add up in this code, but I don't know why it won't add up all the odd negative values. I am still fairly new to coding, so I'd appreciate if you could keep it simple. Thank you.

int total2 = 0;
int[] A = new int[12] {2,3,-5,-67,23,-4,243,-23,2,-45,56,-9};
for (int i = 0; i < A.Length; i++)
{
    if (A[i] % 2 == 1)
    {
        total2 += A[i];
    }
    Console.WriteLine("index: {0}  value: {1} total: {2}",
     i, A[i], total2);
}

Console.ReadKey();
like image 982
TheBoringGuy Avatar asked Dec 16 '22 01:12

TheBoringGuy


1 Answers

For negative numbers % would return -1 or 0. You are checking it against only 1 which is for positive numbers.

You can do:

if ((A[i] % 2 == 1) || (A[i] % 2 == -1))

Or use A[i] % 2 != 0

You can also use Math.Abs like:

if(Math.Abs(A[i] % 2) == 1)
like image 101
Habib Avatar answered Dec 28 '22 23:12

Habib