Answers

Question and Answer:

  Home  Unity Developer

⟩ Can you write a C# method to total all the even numbers in an array of ints?

This is an open-ended coding question that is likely to produce a variety of answers. What you’re really looking for is how the developer chooses to solve the problem. Do they settle for the obvious one-liner, return intArray.Where(i => i % 2 == 0).sum() or will they notice the high probability of overflow and instead opt for something more nuanced like the sample answer below?

static long TotalAllEvenInts(int[] intArray) {

return (from i in intArray where i % 2 == 0 select (long)i).Sum();

}

Experienced C# developers will take this as an opportunity to show off their knowledge of C# language constructs that make simple solutions like the one above possible.

 185 views

More Questions for you: