简体   繁体   中英

Creating an array that starts at n and ends at 0

I'm having difficulty with the action below. I'm not sure how to reverse the array index starting at n and working down to 0. Can someone help me understand this? I'm thinking of using a for loop, but I can't quite visualize how I would do that.

Thanks.

• Add a method called public static int[] generateIntegerArray(int n) to the App class that returns a systematically generated integer array of length n that is reverse sorted starting at n-1 and ending at 0. For example a call generateIntegerArray(5) would result in this array: {4, 3, 2, 1, 0}.

public static int[] generateIntegerArray(int n){

        int[] integerArray = new int[n];
        return integerArray;    
}

Try something like this:

int[] integerArray = new int[n];
for(int i = 0; i < n; i++) {
    integerArray[i] = n - i - 1;
}

return integerArray; 
}

You should just fill that array with values from n-1 to 0

for(int i=0; i<n; i++) {
    integerArray[i] = n-i-1;
}

or

for(int i=n; i>0; i--) {
    integerArray[n-i-1] = i;
}

public static int[] generateIntegerArray(int n){

    int[] integerArray = new int[n];
    for(int i = n - 1; i >= 0; --i){
         integerArray[n - 1 - i] = i;
     }

    return integerArray;    

}

The for loop would run from n - 1 to 0 and the values would be put into array

public static int[] generateIntegerArray(int n){ 

    int[] integerArray = new int[n];
    for(int i = 0; i < n; i++) {
        integerArray[i] = n - i - 1;
    }

    return integerArray; 
}
for (int i = integerArray.length-1 ; i >=0; i--)
{
   integerArray[i] = i;
}

That looks like(if lenght is 6, for example): 6,5,4,3,2,1,0 i - is number in loop, it changes in every loop(i--); So, at the output it will looks like:

integerArray[6]
integerArray[5]
integerArray[4]
integerArray[3]
integerArray[2]
integerArray[1]
integerArray[0]

If I understood you in right way)

int[] integerArray = new int[]{1,2,3,4,5,6,7,8,9};
int[] reversedArray = new int[integerArray.length];
int j = 0;
for (int i = integerArray.length -1; i > 0; i--){
    reversedArray[j++] = integerArray[i];
}

Hope you find this helpful..

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