Krazy Dev - 6 months ago 21

C# Question

I have a function that takes in a list of numbers and will return how many even numbers and odd numbers there are in the list. However, I passed in a list of numbers but I'm getting 0 results.

Here is my function -

`public static string HowManyEvenAndOdds(List<int> numbers)`

{

int numOfOdds = 0;

int numOfEvens = 0;

int numOfBoth = 0;

foreach (int i in numbers) {

bool isEven = i % 2 == 0;

bool isOdd = i % 3 == 0;

numOfBoth = isEven && isOdd ? numOfBoth++ : numOfBoth;

numOfEvens = isEven ? numOfEvens++ : numOfEvens;

numOfOdds = isOdd ? numOfOdds++ : numOfOdds;

}

return string.Format("This list has {0} odd numbers,\n{1} even numbers,\nand {2} numbers that are even and odd.", numOfOdds, numOfEvens, numOfBoth);

}

Any ideas on what I'm doing wrong here? I debugged through it but none of the lists are incrementing.

Thanks

Answer

I agree with Schachaf Gortler's answer as well as p.s.w.g's comment. Just do:

```
foreach (var number in numbers)
{
// A number is even if, and only if, it's evenly divisible by 2
if (number % 2 == 0)
numEvens++;
// A number is odd if, and only if, it's NOT evenly divisible by 2
// Alternatively, a number is odd if it isn't even and vice versa
else
numOdds++;
}
```

As p.s.w.g. mentioned, there's no such thing as a number that's both even and odd, so eliminate that completely.

Incidentally, numOfEvens++ retrieves the value *and then* increments it, which is why your code didn't work.