Reputation: 15
int modeOdd = 0;
System.out.println("Occurence of all existing ODD digits --");
for (int i = 1; i < ary.length; i += 2) { // This prints the array element at the odd indices
if (ary[i] > 0) {
System.out.println("Digit " + i + " : " + ary[i]);
}
}
System.out.println( "\nthe odd digit (s) that has/have the "
+ "higest occurence-");
for (int i = 1; i < ary.length; i += 2){
int newNumber = ary[i];
if (newNumber > ary[modeOdd] ) && ( i % 2 != 0 )){
modeOdd = i;
}
}
System.out.println(modeOdd);
}
The first portion of the code works and prints the array elements at my odd indices. However, the second portion of the code is finding the mode of all my array elements. I don't understand why it is doing this since I start it at index i and increment it by 2. I tried i modulus 2 can't equal 0 and don't see any changes.
What do I need to change? Thank you.
Upvotes: 0
Views: 2836
Reputation: 11284
The bug is this line:
int modeOdd = 0;
You should declare modeOdd = 1
, as currently you declared it to 0, which is not odd, so if ary[0]
contains value greater than any values in odd indices, it will never change.
Note: Be careful if length of the array is less than 2
Upvotes: 3
Reputation: 26077
public class Test {
public static void main(String[] args) {
int modeOdd = 1;
int[] ary = new int[] { 2, 3, 4, 5, 6, 78, 9, 3 };
System.out.println("Occurence of all existing ODD digits --");
for (int i = 1 ; i < ary.length ; i += 2) { // This prints the array element at the odd indices
if (ary[i] > 0) {
System.out.println("Digit " + i + " : " + ary[i]);
}
}
System.out.println("\nthe odd digit (s) that has/have the " + "higest occurence-");
for (int i = 1 ; i < ary.length ; i += 2) {
int newNumber = ary[i];
if (newNumber > ary[modeOdd] && (i % 2 != 0)) {
modeOdd = i;
}
}
System.out.println(modeOdd);
}
}
output
Occurence of all existing ODD digits --
Digit 1 : 3
Digit 3 : 5
Digit 5 : 78
Digit 7 : 3
the odd digit (s) that has/have the higest occurence-
5
Upvotes: 0