Java Program to Print Array Elements Present at Even Positions - The Coding Shala

Home >> Java Programs >> Print Array Elements Present at Even Positions

 In this post, we will learn how to write a Java program to print the array elements that are available at even positions.

Java Program to Print Array Elements Present at Even Positions

Write a Java program to print array elements that are available at even indexes. Positions are starting from 0 in the array.

Example 1:
Input: [1, 2, 3, 4, 5]
Output: 1, 3, 5

Approach:

We will start the for/while loop from index 0 and move the pointer by 2 indexes. 

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void printEvenIndexElements(int[] arr) {
        for (int i=0; i < arr.length; i = i+2) {
            System.out.println(arr[i]);
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 4, 2, 5, 2, 6, 8};
        printEvenIndexElements(arr);
    }
}

Output: 

Elements at even indexes are: 
1
2
2
8


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala