Algorithm Analysis
We will dynamically read the elements of the sequence using a loop and output the odd ones. The number is odd if . The condition for checking the oddness of a number is not correct for a negative . In C, when dividing an odd negative number by 2, the result will be -1.
Algorithm Implementation – Loop
Read the number of input numbers.
scanf("%d",&n);
In the loop, process numbers.
for(i = 0; i < n; i++) { scanf("%d",&val); //if (val % 2 == 1 || val % 2 == -1) printf("%d ",val); if (val % 2 != 0) printf("%d ",val); }
Algorithm Implementation – Array
Declare a working 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, then output 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); int n = con.nextInt(); for(int i = 0; i < n; i++) { int val = con.nextInt(); if (val % 2 != 0) System.out.print(val + " "); } System.out.println(); con.close(); } }
Python Implementation
Read the input sequence of integers into the list lst
.
n = int(input()) lst = list(map(int,input().split()))
In the loop, process numbers of the list lst
.
for x in lst: if x % 2 != 0: print(x, end = " ")
Python Implementation – List
Read the input sequence of integers into the list lst
.
n = int(input()) lst = list(map(int,input().split()))
In the loop, process numbers of the list lst
.
for i in range(n): if lst[i] % 2 != 0: print(lst[i], end = " ")