P
P
PRAIT2020-10-30 10:10:50
Java
PRAIT, 2020-10-30 10:10:50

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

You need to write a program that prints odd numbers from 0 to 20 using only 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 prints numbers from 0 to 20. I don't understand why it doesn't print odd numbers, is everything correct in the code?! Please explain the moment, I will be grateful.

Here is the same program with the addition of continue and everything works as it should. Why is this happening? 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!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2020-10-30
@PRAIT

Well, probably because odd is when the remainder of the division is not equal to zero.
Need to i % 2 == 0replace it with thisi % 2 != 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question