Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a list of integer is odd or even

Tags:

c#

Trying to determine if my list of integer is made of odd or even numbers, my desired output is a list of true an/or false. Can I perform the following operation on the list lst or do I need to create a loop? A is the output.

    List <int> lst = new List <int>();     A = IsOdd(lst); 
like image 594
Arthur Mamou-Mani Avatar asked Sep 15 '13 23:09

Arthur Mamou-Mani


People also ask

How do you check number of a list is even or odd?

Even numbers are divisible by 2. Odd numbers are not. for example 5%2 will return 1 which is NOT zero, (because 5 divided by 2 is 2 with a remainder of 1), therefore it is not even.

How do you check if an integer is odd or even in Python?

num = int (input (“Enter any number to test whether it is odd or even: “) if (num % 2) == 0: print (“The number is even”) else: print (“The provided number is odd”) Output: Enter any number to test whether it is odd or even: 887 887 is odd. The program above only accepts integers as input.

How do you check a number is odd or even in Java?

Now, to check whether num is even or odd, we calculate its remainder using % operator and check if it is divisible by 2 or not. For this, we use if...else statement in Java. If num is divisible by 2 , we print num is even. Else, we print num is odd.

How do you test if a number is odd or even in C#?

One great way to use the modulus operator is to check if a number is even or odd. The modulus is perfect for this sort of test because any even number is, by definition, evenly divisible by 2. So any number that's divided by 2 with no remainder must be even.


1 Answers

You could try using Linq to project the list:

var output = lst.Select(x => x % 2 == 0).ToList(); 

This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.

like image 192
Michael0x2a Avatar answered Oct 08 '22 22:10

Michael0x2a