Home > Back-end >  Calculate the sum of all odd numbers in an array without using if-else or switch-case (C#)
Calculate the sum of all odd numbers in an array without using if-else or switch-case (C#)

Time:03-23

So I tried searching for the solution but most answers I find are about calculating the sum of all odd numbers from 1 to n. What I want to do is to calculate the sum of all odd numbers from an array of random numbers without using conditional statements

For example:

Input: 12, 35, 8, 3, 95, 7, 2
Output: 140

CodePudding user response:

Without any conditional statements, you can use the fact that odd numers and with a 1 in binary representation. Even numbers end with a 0 in binary representation. If you make a bit-wise and number & 1, you will get a 1 for odd numbers and a 0 for even numbers. If you multiply with that value, all odd numbers stay the same and all even numbers become zero. If you add this numbers, you only added odd numers. This can be done with LINQ:

int output = input.Select(x => x * (x & 1)).Sum();

Online demo: https://dotnetfiddle.net/jQSFEO

CodePudding user response:

Use this code.

int[] input = new int[] { 12, 35, 8, 3, 95, 7, 2 };

int Output = input.Where(i => i % 2 == 1).Sum();
  •  Tags:  
  • c#
  • Related