Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does i % 2 == 0 print odd numbers and i % 2 == 1 print even numbers in my for loops? Am I thinking of modulus the wrong way?

//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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading