Google News
logo
Java Program to print the Elements of an Array Present on Odd Position
In the following example of Java program to print the elements of an array present on odd positions :
Program :
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Get the size of the array from the user
        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();

        int[] arr = new int[size];

        // Get the elements of the array from the user
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }

        // Print the elements of the array present on odd positions
        System.out.print("Elements of the array present on odd positions: ");
        for (int i = 0; i < size; i += 2) {
            System.out.print(arr[i] + " ");
        }
    }
}
Output :
Enter the size of the array: 9
Enter the elements of the array:2
5
7
6
9
3
1
15
4
Elements of the array present on odd positions: 2 7 9 1 4 
In this program, we first get the size of the array from the user and then get the elements of the array from the user.

We then iterate over the array and print the elements present on odd positions.

The loop increment by 2 in each iteration to only print the odd positions.