Java Code to Print Elements of an Array at Even Positions

In this program, the objective is to print the elements that are present in even positions within the array. This can be accomplished by traversing the array and incrementing the index variable (i) by 2 in each iteration.

In the above array, elements on even position are b and d.

Algorithm for a Java Code to Print Elements of an Array at Even Positions

STEP 1: Start

STEP 2: Initialize the array arr[] with values {1, 2, 3, 4, 5}.

STEP 3: Print “Elements of given array present on even position:”.

STEP 4: Repeat STEP 5 for each index i starting from 1, incrementing i by 2, until i is less than the length of arr[].

STEP 5: Print the value at arr[i].

STEP 6: End.

Java Code to Print Elements of an Array at Even Positions

public class EvenPosition {  
    public static void main(String[] args) {  
  
        //Initialize array  
        int [] arr = new int [] {1, 2, 3, 4, 5};  
  
        System.out.println("Elements of given array present on even position: ");  
        //Loop through the array by incrementing value of i by 2  
        //Here, i will start from 1 as first even positioned element is present at position 1.  
        for (int i = 1; i < arr.length; i = i+2) {  
            System.out.println(arr[i]);  
        }  
    }  
}

Output:

Elements of given array present on even position:
2
4

In conclusion, the provided Java code aims to print the elements of an array that are present at even positions. It initializes an array with given values and utilizes a loop to iterate through the array, selectively accessing and printing the elements at even positions by incrementing the index variable (i) by 2 in each iteration. Follow tutorials.freshersnow.com to learn more.