Java Program to Print the Elements of an Array Present on Odd Position
An array stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. In an array, if there are “N” elements, the array iteration starts from 0 and ends with “N-1”.
The odd positions in the array are those with even indexing and vice versa.
Example:
Input : arr[] = { 10,20,30,40,50 } Output : 10 30 50 Input : arr1[] = { -5,0,2,5,76,9 } Output : -5 2 76
We will be printing elements at an odd position by two approaches:
- By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0), then print the elements.
- By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1.
Approach 1:
By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0 in the array), then print the elements.
Java
// Java program to print the elements at odd positions import java.util.*; public class PrintOddElementsInArray { public static void main(String[] args) { // Initialized array int inputArray[] = new int [] { 100 , - 500 , 450 , - 200 , 1000 , - 213 , 750 }; System.out.println( "Existing array elements .." ); for ( int i = 0 ; i < inputArray.length; i++) { System.out.println(inputArray[i]); } System.out.println( "Array elements at odd position.." ); // Though the logic looks like taking even position, // if 10,20,30,40,50 are elements we need to get // 10,30,50. So followed the logic like this for ( int i = 0 ; i < inputArray.length; i++) { if (i % 2 == 0 ) { System.out.println(inputArray[i]); } } } } |
Output
Existing array elements .. 100 -500 450 -200 1000 -213 750 Array elements at odd position.. 100 450 1000 750
- Time Complexity: O(n)
- Space Complexity: O(1)
Approach 2:
By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1.
Java
// Java program to print the elements at odd positions import java.util.*; public class PrintOddElementsInArray { public static void main(String[] args) { // Initialized array int inputArray[] = new int [] { 100 , - 500 , 450 , - 200 , 1000 , - 213 , 750 }; System.out.println( "Existing array elements .." ); for ( int i = 0 ; i < inputArray.length; i++) { System.out.println(inputArray[i]); } System.out.println( "Array elements at odd position.." ); int flag = 1 ; for ( int i = 0 ; i < inputArray.length; i++) { if (flag == 1 ) { System.out.print(inputArray[i] + " " ); flag = 0 ; } else flag = 1 ; } } } |
Output
Existing array elements .. 100 -500 450 -200 1000 -213 750 Array elements at odd position.. 100 450 1000 750
- Time Complexity: O(n)
- Space Complexity: O(1)