Here, we will write a java program to print the elements of an array present on odd position. For example, if an array is {2, 12, 23, 7, 6, 15} then we need to display the elements 2, 23 and 6 as they are present in the array on odd positions.
Steps to find even position elements of an Array
- Initialize the array.
- Run a loop starting from 0 till the length of the given array. Use +2 in the increment part of the loop, to only traverse the odd positions in the array.
- Print the current element of the array
- 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 0 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 [] {1, 3, 5, 7, 9, 11, 13}; System.out.println("Array Elements on odd Positions: "); /* Note we are using i = i+2 as we are only traversing odd positions * Important point here is that the array indices start with 0, which * means the odd positions such as 1st, 3rd and 5th positions are having * indices 0, 2, 4 and so on. That's why numbers[0] prints 1st position * element of the array. */ for (int i = 0; i < numbers.length; i = i+2) { System.out.println(numbers[i]); } } }
Output:
Array Elements on odd Positions: 1 5 9 13
Leave a Reply