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

Time:11-04

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

CodePudding user response:

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

% operator is mod operator, if counter % 2 == 0 , then counter is an even number

CodePudding user response:

% 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 i.e (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!

CodePudding user response:

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

  • Related