-2

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;    
}
Nick94107
  • 13
  • 1
  • 3

6 Answers6

1

Try something like this:

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

return integerArray; 
}
MDaniyal
  • 1,097
  • 3
  • 13
  • 29
0

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;
}
ByeBye
  • 6,650
  • 5
  • 30
  • 63
0

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

Rishi
  • 1,163
  • 7
  • 12
0
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; 
}
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
Hemant Patel
  • 3,160
  • 1
  • 20
  • 29
0
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)

Lame Lane
  • 11
  • 1
  • 8
0
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..

SmashCode
  • 741
  • 1
  • 8
  • 14