Home > OS >  Array of total even numbers
Array of total even numbers

Time:10-26

Sorry, I'm still learning how to code. My question is very simple. I'm trying to make an array of int that sum the total of even numbers. My issue is for some reason my code is counting 1 as an even number.

            int[] nums = new[] { 1, 5, 8, 9, 10, 25, 40 };
            int even = 0;
            int odd = 0;
            for (int i =0 ; i < nums.Length; i  )
            {
                if (i % 2 == 0)
                {
                    even  = nums[i];                    
                }

                else
                {
                    odd  = nums[i];                   
                }
            }
                Console.WriteLine(even);
                Console.WriteLine(odd);

The output will be: 59 and 39

CodePudding user response:

You are checking the parity of the loop index i. Use nums[i] in your for loop instead:

if (nums[i] % 2 == 0)
// ... rest of code

CodePudding user response:

In addition to the replies that others have given, you could make the code more efficient by just checking the last bit. Basically, the last bit of the odd numbers will always be 1 so you could do something like

if ((nums[i] & 1) == 0)...

An and operation is normally a lot faster than a unoptimised % operation, which does division and then works out the remainder.

CodePudding user response:

Hey in your code in if() condition u are checking index but but need to check arrays values like nums[i] ==> will give array having values

Your code if (i % 2 == 0)

in place, if index just change it to nums[i]%2

  • Related