Open In App

Java Program to Print the Elements of an Array Present on Even Position

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Example:

Input: [1,2,3,4,5,6]

Output: 2
        4
        6

Input: [1,2]

Output: 2 

Approach:
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.

Example:

Java




// Java Program to Print the Elements of an Array Present on
// Even Position
 
import java.io.*;
import java.util.*;
 
public class EvenPosition {
    public static void main(String[] args)
    {
        // declaration and initialization of array.
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
 
        // iterating through the array using for loop
        for (int i = 1; i < arr.length; i = i + 2) {
 
            // print element to the console
            System.out.println(arr[i]);
        }
    }
}


Output

2
4
6

Time Complexity: O(n) where n is the size of an array

Auxiliary Space: O(1)


Last Updated : 21 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads