This is the Java Program to Print Even Elements at Even Index Number.
Given an array of integers, print the even numbers present at even index numbers.
Example:
Array = [2,1,4,4,5,7]
Output = 2 4
Iterate through the array, and check whether the current index is even or odd if it is even, 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 Even 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 Even Index Number
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EvenIndexedOddElements {
// Function to even numbers present at even 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 if the index and the element at the index are both even.
3. The element is displayed if the condition is true.
Time Complexity: O(n) where n is the number of elements in the array.
Case 1 (Simple Test Case - Even elements at even index): Enter the size of the array 6 Enter array elements 2 1 4 4 5 7 Output 2 4 Case 2 (Simple Test Case - Odd elements at even index): Enter the size of the array 5 Enter array elements 1 2 3 4 5 Output
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Java Internship
- Apply for Computer Science Internship
- Practice Programming MCQs
- Practice BCA MCQs
- Check Programming Books