Array adding odd values

I have a little problem: I have all the odd numbers that need to be added to this code, but I don't know why it won't contain all the odd negative values. I'm still pretty new to coding, so I'd appreciate it if you could keep it simple. Thanks.

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();
+4
source share
3 answers

For negative numbers, %will return -1or 0. You only check it for 1which 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 , for example:

if(Math.Abs(A[i] % 2) == 1)
+10

IF, .

@NullUserExceptions,

if( Convert.ToBoolean( A[i] % 2 ) ){
    sum += i;
}

, .

+1

If you use LINQ, this can be simplified as follows:

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] A = new int[12] {2,3,-5,-67,23,-4,243,-23,2,-45,56,-9};

            // using LINQ method chaining syntax 
            var result = A.Where(x => x % 2 != 0).Select(r => r);

            // Or comprehensive syntax
            //var result = from r in
            //             A.Where(x => x % 2 != 0)
            //             select r;
            var total2 = result.Sum();
            int i = 0;
            foreach (var r in result)
            {
               Console.WriteLine("index: {0}  value: {1} total: {2}", i, r, total2);
               i++;
            }
            Console.ReadKey(true);
        }            
    }
}
+1
source

Source: https://habr.com/ru/post/1529450/


All Articles