Java Program to Return the Elements at Odd Positions in a List
Given a List, the task is to return the elements at Odd positions in a list. Let’s consider the following list.
Clearly, we can see that elements 20, 40, 60 are at Odd Positions as the index of the list is zero-based. Now we should return these elements.
- Initialize a temporary value with zero.
- Now traverse through the list.
- At each iteration check the temporary value if value equals to odd then return that element otherwise just continue.
- After each iteration increment the temporary value by 1.
- However, this can be done without using temporary value. Since the data in the list is stored using fixed index therefore we can directly check if the index is odd or even and return the element accordingly
Elements at odd position are : 20 40 60
- Traverse the list starting from position 1.
- Now increment the position by 2 after each iteration. By doing this we always end up in an odd position.
- Iteration 1: 1+2=3
- Iteration 2: 2+3=5
- Iteration 3: 5+2=7
- And so on.
- Return the value of the element during each iteration.
Elements at odd positions are : 20 40 60