How to output odd numbers from 0 to 20 using FOR?

  • 0
    You need to write a program that prints odd numbers from 0 to 20 using exclusively a for loop.

    public class TestClass {
        public static void main(String[] args) {
            for (int i = 0; i < 20; i++) {
                if (i % 2 == 0) {
                    System.out.println(i);
                }
            }
        }
    }


    This program displays numbers from 0 to 20. I don’t understand why it doesn’t print odd numbers, everything seems to be correct in the code ?! Please explain the moment, I will be grateful.

    Here's the same program with continue added and everything works as it should. Why it happens? After all, even without continue, odd numbers should be printed, or am I wrong? What is the reason? I don't understand ..

    public class TestClass {
        public static void main(String[] args) {
            for(int i=0; i < 20; i++) {
                if(i%2 == 0) { 
                    continue;
                }
                System.out.println("Number=" + i); 
            }
        }
    }


    Thank you!
    Java Aiden Foster, May 26, 2020

  • 1 Answers
  • 0
    Well, probably because odd is when the remainder of a division is not zero.

    You need this i% 2 == 0 replace with this i% 2! = 0
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!