This is the Java Program to Print Even Elements at Odd Index Number.
Given an array of integers, print the even numbers present at odd index numbers.
Example:
Array = [2,1,4,4,5,7]
Output = 4
Iterate through the array, and check whether the current index is even or odd if it is odd, then check the element at that index to be even or odd, print the element if it is even.
Here is the source code of the Java Program to Print Even Elements at Odd Index Number. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Print Even Elements at Odd Index Number
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EvenIndexedOddElements {
// Function to even numbers present at odd index
static void printEvenIndexedElements(int[] array){
int i=0;
for(i=0; i<array.length; i++){
if(i%2 != 0 && array[i]%2 ==0){
System.out.print(array[i] + " ");
}
}
}
// Function to read input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
}
System.out.println("Output");
printEvenIndexedElements(array);
}
}
1. In function printEvenIndexedElements, the loop for(i=0; i<array.length; i++) is used to iterate through the array.
2. The condition if(i%2!=0 && array[i]%2==0), checks whether the current index is odd and the element at that index is even.
3. The element is printed if the above mentioned condition is true.
Time Complexity: O(n) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the size of the array 6 Enter array elements 2 1 4 4 5 7 Output 4 Case 2 (Simple Test Case - another example): Enter the size of the array 8 Enter array elements 12 34 45 32 76 55 567 346 Output 34 32 346
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Information Technology MCQs
- Apply for Computer Science Internship
- Check Programming Books
- Check Java Books
- Practice BCA MCQs