简体   繁体   中英

How can I make it so my while-loop only prints even numbers? Java Eclipse IDE

Beginner here. For my coding class, we have an assignment that requires us to print numbers 1-20, but configure it so that it only outputs even numbers. Here is what I have so far but I'm quite stuck. He says to put an if statement and use the "%" operator but I've no idea where to put them.

    int counter = 1;
    System.out.println("Part 2 - Even Numbers");
    while (counter <= 20)
    {
        //if (counter 
        System.out.printf("%d ", counter);
        counter++;
    } // end while loop

Instructions for assignment

My Output

CORRECT Output

  if(counter % 2 == 0){
      System.out.printf("%d ", counter);
  }
  counter++;

% operator is mod operator, counter % 2 == 0 counter is even number

use fori

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

% is the remainder operation

% is an arithmetic operator, it is called MODULO . Modulo operator returns the remainder of 2 numbers. In this case, we use a modulo to find out whether a number is even or odd.

odd%2 returns 1

even%2 returns 0

The while loop loops through the first 20 elements. So we put an if statement before printing the element. If the counter is an even number ie (counter%2 == 0) we print that.

This is the code that prints even numbers:

        int counter = 0;
        System.out.println("Part 2 - Even Numbers");
        while (counter <= 20)
        {
            if (counter%2 == 0){
                System.out.printf("%d ", counter);
            }
            counter++;
        } // end while loop

This can also be done without using MODULO operator:

        int counter = 0;
        System.out.println("Part 2 - Even Numbers");
        while (counter <= 20)
        {
            System.out.printf("%d ", counter);
            counter+=2;
        } // end while loop

YW!

Keep learning!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM