In this tutorial, we will learn writing program in Python to create an array (list in case of python) and print the odd elements stored in the array (list).
Problem Statement
Our program will first take the input of array (list) size and then the elements of the array (list) from the user. And then prints all the odd numbers from the elements of the input 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 1, 3.
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 9, 7, 5.
[elementor-template id=”5253″]
Our logic to print odd 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 the ‘if-else’ conditional statement to check if the element is odd.
- Print the odd numbers from the array (list)
Algorithm to print odd 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
[elementor-template id=”5256″]
Python program to print odd numbers from array (list)
Output 1:
Explanation:
For the input array [32, 11, 45, 2, 33], while iterating the elements of the array (list). For elements 11, 45, and 33, the if-condition is satisfied as they are odd numbers and then the numbers 11, 45, and 33 are printed as the output of the program.
[elementor-template id=”5257″]
Output 2:
Explanation:
For the input array [12, 13, 14, 15, 16, 17], while iterating the elements of the array (list). For elements 13, 15, and 17, the if-condition is satisfied as they are odd numbers and then the numbers 13, 15, and 17 are printed as the output of the program.