I can not figure out how to output the elements of the array in the console: all even numbers from 1 to 20. Help, please.

public static void main(String[] args) { int [] a = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; for (int i = 0; i < a.length; i++) { a[i] = (i+1)*2; System.out.println(Arrays.toString(a)); } } 
  • one
    You already have "all even numbers from 1 to 20" in the array, you just need to display them, without any additional manipulations. Or in the condition of some kind of error, now all this does not seem meaningful. Maybe you just need to display all even numbers up to 20? Or select them from an arbitrary array? - PinkTux

3 answers 3

how to output array elements in the console: all even numbers from 1 to 20

Like this:

 public static void main(String[] args) { int [] a = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; for (int i = 0; i < a.length; i++) { System.out.printf( "%d\n", a[i] ); } } 

Or you have something wrong with either the task or with the input data.

    I answer from the tablet for this syntax can not answer

     For(int=0;i<a.length();i++){ If(a[i]%2==0) System.out.println(a[i]); } 

      If you want to display all the even numbers of the array in which there may be odd numbers, you can use this approach:

        int [] array = {2, 3, 5, 8, 10, 11, 14, 15, 18, 20}; for(int i=0;i<array.length;i++) { if(array[i]%2==0) { System.out.println("Index: "+i+"; Number: "+array[i]); } } 

      If you want to display only numbers, then you can do with foreach

       for (int number : array) if (number % 2 == 0) System.out.println(number); 

      Conclusion:

       Index: 0; Number: 2 Index: 3; Number: 8 Index: 4; Number: 10 Index: 6; Number: 14 Index: 8; Number: 18 Index: 9; Number: 20