In this program, the objective is to print the elements of the array that are present in odd positions. This can be achieved by iterating through the array and incrementing the index variable (i) by 2 in each iteration, ensuring that only elements at odd positions are accessed.
In the above array, the elements present in odd positions are a, c, and e.
Algorithm for a Java Code to Print Elements of an Array at Odd 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 odd position:”.
STEP 4: Repeat STEP 5 for each index i starting from 0, 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 Odd Positions
public class OddPosition { 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 odd position: "); //Loop through the array by incrementing value of i by 2 for (int i = 0; i < arr.length; i = i+2) { System.out.println(arr[i]); } } }
Output:
Elements of given array present on odd position: 1 3 5
In conclusion, the provided Java code is designed to print the elements of an array that are present at odd positions. It initializes an array with given values and utilizes a loop to iterate through the array, selectively accessing and printing the elements at odd positions by incrementing the index variable (i) by 2 in each iteration. Follow tutorials.freshersnow.com to learn more.