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();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With