Use the following code which initializes an array x with 100

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.

Solution

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

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.Rand

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site