This is the Java Program to Print Odd Elements at Even Index Number.
Given an array of integers, print the odd numbers present at even index numbers.
Example:
Array = [2,1,4,4,5,7]
Output = 5
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 odd.
Here is the source code of the Java Program to Print Odd 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 Odd Elements at Even Index Number
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EvenIndexedOddElements {
// Function to odd 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 whether the current index is even and the element at that index is odd.
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 5 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 45 567
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Java Internship
- Apply for Computer Science Internship
- Check Programming Books
- Practice Programming MCQs
- Practice BCA MCQs