简体   繁体   中英

For loops in Java (using Arrays)

Create an array, type int, length 10. Initialize it with the multiple of 2.

Print it out to the console Now print it in reverse order.

Expected output: // (must use for loop)

2 4 6 8 10 12 14 16 18 20

20 18 16 14 12 10 8 6 4 2

This is what I have done so far :

    int [] values = new int [10];
    for (int i=2 ; i <= values.length; i ++)
    {
        if (i%2 == 0)
        System.out.println(i);
    }

Output: 2 4 6 8 10

It seems it only print up to the value of 10, but how do i get it to print a length of 10?

Create an array, type int, length 10. Initialize it with the multiple of 2.

In your code snippet you are not Initializing the array but simply printing the values to the console. You'll have to initialize it using either the loop or as follows:

int[] values = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};

If you want it to be initialized by writing the loop then here is the corrected code snippet:

public static void main (String[] args) throws Exception {
    int[] values = new int[10];
    values[0] = 2;
    System.out.print(values[0]);
    for (int i = 1; i < values.length; i++) {
        values[i] = values[i-1] + 2;
        System.out.print(" " + values[i]);
    }
}
public static void main(String[] args)
    {
        int[] arr = new int[10];      //declaring arr
        arr[0] = 2;       //giving arr a start point

        for(int i = 1 ; i<arr.length;i++)     //set values for arr
            arr[i] = arr[i-1] +2;        //each value is previous value + 2
        for(int i = 0; i<arr.length;i++)
            System.out.print(arr[i] + " ");     //prints it from 0 to 9
        System.out.println();
        for(int i = 0;i<arr.length;i++)
            System.out.print(arr[9 - i]+ " ");    //prints it backward
    }

Descriptions are on the code.

int [] values = new int [10];
    for (int i=0 ; i <= values.length; i++)
    {
        values[i] = (i+1)*2; //initialize
    }
//Now iterate and print

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM