Krazy Dev
Krazy Dev

Reputation: 182

Code not returning expected number of even and odds

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

Upvotes: 1

Views: 134

Answers (4)

user6996876
user6996876

Reputation:

Use the Linq Count extension.

int numOfOdds = numbers.Count(x => x % 2 != 0);
int numOfEvens = numbers.Count(x => x % 2 == 0);

Of course you don't need to evaluate both expressions, as per the comment below.

Upvotes: 1

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.

Upvotes: 5

Brian THOMAS
Brian THOMAS

Reputation: 534

I think you should have a look at your test for isOdd

Upvotes: 1

Shachaf.Gortler
Shachaf.Gortler

Reputation: 5745

your are not calculating odd in the correct way i%3 does not catch 5 which is also an odd number, try this instead

 bool isEven = i % 2 == 0;
 bool isOdd =!isEven;

Upvotes: 6

Related Questions