Reputation: 15
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
Upvotes: 1
Views: 2881
Reputation: 469
You can use foreach loop:
foreach (var num in nums)
{
if (num % 2 == 0)
{
even += num;
}
else
{
odd += num;
}
}
Upvotes: 1
Reputation: 31
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
Upvotes: 1
Reputation: 8237
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.
Upvotes: 3
Reputation: 395
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
Upvotes: 3