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)
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")
Step-by-step 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
mylist.append(listlent)
for i in range(listlent):
num = int(input(": "))
mylist.append(num)
The next two lines initialize even and odd to 0, respectively
evens = 0
odds = 0
The following iteration if a list item is even or odd
for i in range(1,listlent+1):
if mylist[i]%2==0:
evens=evens+1
else:
odds=odds+1
This checks and prints if all list items is odd
if(evens == 0 and odds != 0):
print("All Odds")
This checks and prints if all list items is even
elif(evens != 0 and odds == 0):
print("All Even")
This checks and prints if all list items is neither even nor odd
else:
print("Neither")