Question:
Write a program that reads a list of integers, and outputs whether the list contains all even numbers, odd numbers, or neither. The input begins with an integer indicating the number of integers that follow. Assume that the list will always contain less than 20 integers.
Answer:
Written in Python
listlent = int(input("Length of List: "))
mylist = []
mylist.append(listlent)
for i in range(listlent):
num = int(input(": "))
mylist.append(num)
<em> </em>
evens = 0
odds = 0
for i in range(1,listlent+1):
if mylist[i]%2==0:
evens=evens+1
else:
odds=odds+1
if(evens == 0 and odds != 0):
print("All Odds")
elif(evens != 0 and odds == 0):
print("All Even")
else:
print("Neither")
Explanation:
This prompts user for length of the list
listlent = int(input("Length of List: "))
This initializes an empty list
mylist = []
The following iteration reads the list items from the user
<em>mylist.append(listlent)</em>
<em>for i in range(listlent):</em>
<em> num = int(input(": "))</em>
<em> mylist.append(num)</em>
The next two lines initialize even and odd to 0, respectively
<em>evens = 0</em>
<em>odds = 0</em>
<em />
The following iteration if a list item is even or odd
<em>for i in range(1,listlent+1):</em>
<em> if mylist[i]%2==0:</em>
<em> evens=evens+1</em>
<em> else:</em>
<em> odds=odds+1</em>
This checks and prints if all list items is odd
<em>if(evens == 0 and odds != 0):</em>
<em> print("All Odds")</em>
This checks and prints if all list items is even
<em>elif(evens != 0 and odds == 0):</em>
<em> print("All Even")</em>
This checks and prints if all list items is neither even nor odd
<em>else:</em>
<em> print("Neither")</em>