The task is to print all the elements that are present in even position. Consider an example, we have an array of length 6, and we need to display all the elements that are present in 2,4 and 6 positions i.e; at indices 1, 3, 5.
Input: [1,2,3,4,5,6] Output: 2 4 6 Input: [1,2] Output: 2
1) First take a class with the name DisplayElementAtEvenPosition.
2) Then inside the main function, declare and initialize an array with values mentioned in the above example.
3) Now in -order to display the values at even position we need to iterate through the array.
4) For this purpose take a for-loop and iterate through the array while incrementing the value with 2 as we need the values at even position.
5) Once done with the approach, compile it to get the output.
2 4 6
Time Complexity: O(n) where n is the size of an array
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.