A sequence of n integers is given. Print all its odd
elements.
Input. The first line contains the integer n (n ≤ 100). The second line contains n integers, each of which does not
exceed 100 in absolute value.
Output. Print all the odd elements of the
sequence in the order they appear in the input.
Sample input |
Sample output |
7 14 17 16 3 7 19 9 |
17 3 7 19 9 |
loops
Read the elements of the sequence one by one using a
loop and immediately print the odd
ones. A number val is considered odd if val % 2 ≠ 0. However, the condition val % 2 == 1 is
incorrect for checking the oddness of negative values of val. In the C
language, dividing a negative odd number by 2 results in -1.
Algorithm implementation – loop
Read the number of input values n.
scanf("%d",&n);
Process the n numbers sequentially in a loop.
for(i = 0; i < n; i++)
{
scanf("%d",&val);
If the number val is odd, print it.
//if (val % 2 == 1 || val % 2 == -1) printf("%d
",val);
if (val % 2 != 0) printf("%d
",val);
}
Algorithm implementation – array
Declare an array.
int m[101];
Read the input sequence of integers into the array m.
scanf("%d",&n);
for (i = 0; i < n; i++)
scanf("%d", &m[i]);
Iterate through the numbers in the array. If m[i] is odd, print it.
for (i = 0; i < n; i++)
if (m[i] % 2 !=
0) printf("%d ", m[i]);
printf("\n");
Java implementation
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
Read the number of input values n.
int n = con.nextInt();
Read the input sequence of n integers.
for(int i = 0; i < n; i++)
{
int val = con.nextInt();
If the number val is odd, print it.
if (val % 2 != 0) System.out.print(val + " ");
}
System.out.println();
con.close();
}
}
Python implementation
Read the input data.
n = int(input())
lst = list(map(int,input().split()))
Process the n numbers in the list lst using a
loop.
for x in lst:
If the number x is odd, print it.
if x % 2 != 0:
print(x, end = " ")
Python implementation – list
Read the input data.
n = int(input())
lst = list(map(int,input().split()))
Process the n numbers in the list lst using a
loop.
for i in
range(n):
If the number lst[i] is odd, print it.
if
lst[i] % 2 != 0:
print(lst[i],end = " ")
Python implementation – create a list
Read the input data.
n = int(input())
lst = list(map(int,input().split()))
Create a list p that
contains only odd
integers.
p = [x for x in
lst if x % 2
!= 0]
Print the answer.
print(*p)