Here, we will write a java program to print the elements of an array present on even position. For example, if an array is {1, 4, 8, 3, 9, 17} then we need to display the elements 4, 3 and 17 as they are present in the array on even positions.
Steps to find even position elements of an Array
- Initialize the array.
- Run a loop starting from 1 till the length of the given array. Use +2 in the increment part of the loop, to only traverse the even positions in the array.
- Display current array element
- End of the program.
Program to display array elements on even positions
Please go through the comments mentioned in the following program to understand why we are starting the loop from 1 and why are using i=i+2
in the increment part of the loop.
public class JavaExample { public static void main(String[] args) { //Initializing the array int [] numbers = new int [] {5, 12, 16, 3, 9, 7, 1, 100}; System.out.println("Array Elements on even Positions: "); /* Note we are using i = i+2 as we are only traversing even positions * Important point here is that the array indices start with 0, which * means the even positions such as 2nd, 4th and 6th positions are having * indices 1, 3, 5 and so on. That's why numbers[1] prints 2nd position * element of the array. */ for (int i = 1; i < numbers.length; i = i+2) { System.out.println(numbers[i]); } } }
Output:
Array Elements on even Positions: 12 3 7 100
Leave a Reply