This is the Java Program to Print Odd Elements at Odd Index Number.
Given an array of integers, print the odd numbers present at odd index numbers.
Example:
Array = [2,1,4,4,5,7]
Output = 1,7
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 odd.
Here is the source code of the Java Program to Print Odd 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 Odd Elements at Odd Index Number
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class OddIndexedOddElements {
// Function to print Odd Elements present at Odd Index Number
static void printOddIndexedElements(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 user 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");
printOddIndexedElements(array);
}
}
1. In function printOddIndexedElements(), the loop for(i=0; i<array.length; i++) iterates through the array.
2. Then using the condition if(i%2 != 0 && array[i]%2 != 0), we first check whether the current index is odd.
3. If the index is odd, then we check the element at that index (the condition after the && operator), if the element is odd, then display the element.
Time Complexity: O(n) where n is the number of elements in the array.
Case 1 (Positive test Case - having odd elements at odd index): Enter the size of the array 6 Enter array elements 2 1 4 4 5 7 Output 1 7 Case 2 (Negative test Case - no odd element present at odd index): Enter the size of the array 5 Enter array elements 1 2 3 4 5 Output
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice BCA MCQs
- Apply for Computer Science Internship
- Practice Programming MCQs
- Practice Information Technology MCQs
- Check Java Books