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

Time Complexity, Space Complexity, Asymptotic Notations - The Coding Shala

Java Method Overloading - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Binary Number with Alternating Bits LeetCode Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala