In this tutorial, we will learn writing python program to create an array (list in case of python) and print the all even numbers stored in the array (list).
Problem Statement
Our Problem statement is like, We have to write an program that will first take the input of array (list) size and then the elements of the array (list). And then prints all the even numbers from the elements from the array (list).
For example:
Case 1: if the user inputs 4 as array (list) size and the array (list) elements as 1,2,3,4.
The output should be 2, 4.
Case 2: if the user inputs 5 as array (list) size and the array (list) elements as 9,8,7,6,5.
The output should be 8, 6.
[elementor-template id=”5253″]
Our logic to print even numbers from array (list)
- Our program will take input to fix the size of the array (list).
- Then our program will run for a ‘for loop’ to take the inputs from the user. The inputs will be the elements (or the content) of the array (list).
- Then, for each element of the array (list), our program will use ‘if-else’ conditional statement to check if the element is even.
- We will check element is even or not by calculating n%2, If this will return true it mean element is even number.
- Print the even numbers from the array (list).
[elementor-template id=”5257″]
Algorithm to print even numbers from array (list)
Step 1: Start
Step 2: take an input from the user (let’s say size).
Step 3: Create an empty list and a variable sum with value assign is 0.
Step 4: for i in range(0,size):
elem=int(input(“Please give value for index “+str(i)+”: “))
arr.append(elem)
Step 5: for i in range(0,size):
if arr[i]%2==0:
print(arr[i],end=’ ‘)
Step 6: Stop
Python code to print even numbers from array (list)
Output 1:
Explanation:
For the input array [23, 11, 22, 44, 65], while iterating the elements of the array (list). For elements 22 and 44, the if-condition is satisfied and then the numbers 22 and 44 are printed as the output of the program.
Output 2:
Explanation:
For the input array [1, 2, 3, 4, 5], while iterating the elements of the array (list). For elements 2 and 4, the if-condition is satisfied and then the numbers 2 and 4 are printed as the output of the program.