Wypisywanie liczb parzystych od 0 do 100

0

jak w temacie. liczby wypisuje mi tylko od 2-100

public class cwiczenie2 {
    public static void main(String[] args){
        
        int a = 0;
        
        while(a<100){
            while(++a%2 == 0){
                
                System.out.println(a);
                
                
            }
        }
    }
    
}
0

Skopiowałeś ten kod skądś i nie wiesz co robi?

++a to preinkrementacja, a więc zanim a zostanie wypisane to zostanie zinkrementowane. Proste.

0

napisalem sam. wiec jak to powinienem zrobic ? rozumiem to co mowisz. probowalem uzyc post ale wtedy wyswietla liczby 1,3,5,7,9,11 itd

1
System.out.println(a-1);
0

wtedy musze zastosowac <=. czy tak bd optymalnie?

public class cwiczenie2 {
    public static void main(String[] args){
        
        int a = 0;
        
        while(a<=100){
            while(a++%2 == 0){
                
                System.out.println(a-1);
                
                
                
            }
        }
    }
    
}
3
for(int i = 2; i <= 100; i += 2) System.out.println(i);
0

musze to zrobic z while

0

się uczę JAvy to umiem:

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

ten sam kod co powyzej ale z while

2
int i=-2;
while((i+=2)<=100) System.out.println(i);
0

Można też tak:

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Even_1 {
	public static void main(String[] args) {
		OutputStream out = new BufferedOutputStream(System.out);
	    for(int i = 0; i <= 100; i++) {  
	    	if ((i & 1) != 0) 
	    		continue;
		      try {
				out.write((i + "\n").getBytes());
			} catch (IOException ex) {
				ex.printStackTrace();
			} 
	    }
	    try {
			out.flush();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Sporo szybciej, niż przy użyciu System.out.println(). No i w dodatku zaszpanujesz operacją na ostatnim bicie :)

0
public static void main(String[] args) {
		int a = 0;

		while (a <= 100) {
			if (a % 2 == 0) {
				System.out.print(a + ", ");
			}
			a++;
		}

	}

wynik:

0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100,

1 użytkowników online, w tym zalogowanych: 0, gości: 1