Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use the following code, which initializes an array x with 1000 random integers,

ID: 3920986 • Letter: U

Question

Use the following code, which initializes an array x with 1000 random integers, to answer the questions a and b.

java.util.Random generator = new java.util.Random( );//accessing Random class
final int MAX = 1000;
int[] x = new int[MAX];
for( int j = 0; j < MAX; j++ )
{
x[j] = generator.nextInt( MAX ) + 1;
}

a. Write partial code to print all array elements of x in reverse order (one array element per line)

b. Write partial code to compute the average of all elements and store it into a double variable named average.

Explanation / Answer

public class RandomArray {

   public static void main(String[] args) {
       java.util.Random generator = new java.util.Random();// accessing Random
                                                           // class
       final int MAX = 1000;
       int[] x = new int[MAX];
       for (int j = 0; j < MAX; j++) {
           x[j] = generator.nextInt(MAX) + 1;
       }

       // code to print all array elements of x in reverse order (one array
       // element per line)
       for (int j = MAX - 1; j >= 0; j--) {
           System.out.println(x[j]);
       }

       // code to compute the average of all elements and store it into a
       // double variable named average.
       double average, sum = 0.0d;
       for (int j = 0; j < MAX; j++) {
           sum += x[j];
       }
       average = sum / MAX;
       System.out.println("Average :" + average);

   }
}

OUTPUT:

520
832
163
644
204
513
.
.
.

Average :500.45

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote