-2

Why the attached code gives me this out put :

3 , 5 , 7 , 9

it should show the even values only

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

3 Answers3

0

This is because you are doing i++ inside the if. The post increment there means that the value evaluated in the condition is pre-increment but when you reach the print statement, it has been incremented. Try incrementing after the if.

codetective
  • 86
  • 2
  • 9
0

Try this code:

public static void main (String [] args){
int i = 1;

while ( i < 10 ){
    if ((++i)%2 == 0){
        System.out.println(i);
      
    }
}}
nissim abehcera
  • 821
  • 6
  • 7
0
  • The evaluation is done prior to the increment.
  • the printing is done after the increment.
int i = 1;

while ( i < 10 ){
    if ((i++)%2 == 0)  {        // i evaluated true while "even" before increment
        System.out.println(i);  // printing post increment i 
    }
}

To correct this, simply move the autoincrement to the left of i.

WJS
  • 36,363
  • 4
  • 24
  • 39