Friday, December 27, 2024
Google search engine
HomeLanguagesJavaJava Program to Print the Elements of an Array Present on Even...

Java Program to Print the Elements of an Array Present on Even Position

The task is to print all the elements that are present in even position. Consider an example, we have an array of length 6, and we need to display all the elements that are present in 2,4 and 6 positions i.e; at indices 1, 3, 5. 

Example:

Input: [1,2,3,4,5,6]

Output: 2
        4
        6

Input: [1,2]

Output: 2 

Approach:
1) First take a class with the name DisplayElementAtEvenPosition.
2) Then inside the main function, declare and initialize an array with values mentioned in the above example.
3) Now in -order to display the values at even position we need to iterate through the array.
4) For this purpose take a for-loop and iterate through the array while incrementing the value with 2 as we need the values at even position.
5) Once done with the approach, compile it to get the output.

Example:

Java




// Java Program to Print the Elements of an Array Present on
// Even Position
 
import java.io.*;
import java.util.*;
 
public class EvenPosition {
    public static void main(String[] args)
    {
        // declaration and initialization of array.
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
 
        // iterating through the array using for loop
        for (int i = 1; i < arr.length; i = i + 2) {
 
            // print element to the console
            System.out.println(arr[i]);
        }
    }
}


Output

2
4
6

Time Complexity: O(n) where n is the size of an array

Auxiliary Space: O(1)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments