Java Program to Print Odd Elements at Even Index

In Java, arrays are commonly used to store collections of data. When working with arrays, you might encounter scenarios where you need to perform operations based on specific criteria, such as printing elements that are odd and are located at even indices. In this section, we will create a Java program that achieves this, providing a detailed explanation and complete code.

Problem Statement

Given an array of integers, print the elements that are odd and are located at even indices.

Approach

  1. Iterate through the Array: Loop through the array using a for loop.
  2. Check Index and Value: For each element, check if its index is even and its value is odd.
  3. Print the Element: If both conditions are met, print the element.

Steps

  1. Initialize the Array: Define the array with some sample values.
  2. Loop Through the Array: Use a for loop to iterate through the array.
  3. Check Conditions: Use the modulus operator to check if the index is even and the element is odd.
  4. Print Matching Elements: Print the elements that meet the criteria.

File Name: OddElementsAtEvenIndex.java

Output:

 
Odd elements at even indices:
Element at index 2: 15
Element at index 4: 19
Element at index 6: 23   

Explanation

An array is initialised with sample integers in the Java program to output odd elements at even indices, and a for loop is used to iterate over the array. We verify whether the index even applies the criterion i % 2 == 0 for every element. If the index is even, we use the condition array[i] % 2!= 0 to determine if the element at that index is odd. We print the element if the two requirements are satisfied.

Conclusion

This Java program demonstrates how to identify and print odd elements that are located at even indices in an array. By using simple loops and conditional statements, you can efficiently filter, and display elements based on specific criteria. This technique can be extended to more complex scenarios and is a fundamental skill in array manipulation in Java.