Menu
Topics Index
...
`

Print even numbers - Java Example Program


Print even numbers
class PrintEvenNumbers
{
    public static void main(String arg[])
    {
        for(int i = 1; i < 5; i++)
        {
            System.out.println("processing " + i); // LINE A
        
            boolean odd = (i % 2 == 1);
        
            if( odd ) continue; // LINE B
        
            System.out.println(i + " is even"); // LINE C
        }    
    }
}
OUTPUT

processing 1
processing 2
2 is even
processing 3
processing 4
4 is even

DESCRIPTION

Here i is iterated from 1 to 5, when i = 1, it first prints processing 1 and then variable odd is evaluated which will be true. So continue will be called at LINE B. This will cause the control to go back to the first statement which is LINE A. LINE C will not be executed.
Next when i becomes 2, it prints processing 2 and odd will become false, so continue will not be called. So LINE C executes, printing 2 is even. These iterations continue until i becomes 5 and prints the rest of output.

THINGS TO TRY
  • In the above program try to print odd numbers instead of even numbers.
  • Try for the below code.
    int i = 0;
    while (i < 5)
    {
        System.out.println("value of i: " + i);
        i++;
        if (true)
            continue; // LINE A    
        System.out.println("value after continue: " + i); // LINE B
    }
    The output for the above code is :
    value of i: 0
    value of i: 1
    value of i: 2
    value of i: 3
    value of i: 4

    We can see LINE B is not executed because of continue at LINE A.
  • Remove if condition at LINE A in the above sample code to see a compilation error since continue should be in a if block if it is not the last sentence.

© meritcampus 2019

All Rights Reserved.

Open In App