//Array:
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9 , 10}
nums ==> int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
//for-loop that prints odd numbers: Shouldn’t i % 2 == o print even numbers?
jshell> for(int i = 0; i < nums.length; i++){
...> if(i % 2 == 0){ // even numbers?
...> System.out.println(nums[i]);
...> }
...> }
1
3
5
7
9
//for loop that prints even numbers: Shouldn’t i %2 == 1 print odd numbers?
jshell> for(int i = 0; i < nums.length; i++){
...> if(i % 2 == 1){ // odd numbers?
...> System.out.println(nums[i]);
...> }
...> }
2
4
6
8
10
>Solution :
Arrays are zero-indexed in Java (and most languages derived from C). This means we start counting from 0; an array with 10 elements has indices 0, 1, …, 9.
So nums[0] is the 1st element of your array, i.e. 1. When the index i is 0, i % 2 == 0 will be true (because i is an even number). So you’ll print an odd number (nums[i]) when i is even.