Display even and odd numbers in java using for loop

Let’s learn to display even and odd numbers in java using for loop.

Display even and odd numbers in java using for loop

So to check if number is even or odd number, first the given number is divided by 2.

Here we are using two for loops, one to get input from user and another to print even and odd numbers.

Using modulus operator we have to check if remainder is zero.

If the remainder is zero then given number is even number. If the remainder is one then given number is odd number.

Here’s the java program to print even and odd numbers using for loop.

import java.util.Scanner;
public class EvenOddUsingForLoop
{
   public static void main(String[] args)
   {
      int a;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number(max) to print all even and odd until: ");
      int number = sc.nextInt();
      System.out.println("Even numbers from 1 to " + number + " are: \n");
      for(a = 1; a <= number; a++)
      {
         if(a % 2 == 0)
         {
            System.out.print(a + "\n");
         }
      }
      System.out.println("Odd numbers from 1 to " + number + " are: \n");
      for(a = 1; a <= number; a++)
      {
         if(a % 2 == 1)
         {
            System.out.print(a + "\n");
         }
      }
      sc.close();
   }
}


Output:

Enter number(max) to print all even and odd until: 10
Even numbers from 1 to 10 are:
2
4
6
8
10
Odd numbers from 1 to 10 are:
1
3
5
7
9