In: Computer Science
*****IN JAVA*****
Write a code snippet that initializes an array with ten random integers and then prints
the following output:
a. every element (on a single line)
b. every element at an even index (on a single line)
c. every even element (on a single line)
d. all elements in reverse order (on a single line)
e. only the first and last elements (on a single line)
import java.util.Random;
public class GenRandomInteger{
public static void main(String args[]){
//initialize an long array of length 10
long[] randInt = new long[10];
//create Random class object
Random random = new Random();
//iterate the loop 10 times, to generate 10 random integers
for(int i=0; i<10;i++){
//Generate Random integer
randInt[i] = random.nextInt();
}
//a) every element (on a single line)
for(int i = 0; i < 10; ++i)
System.out.print(randInt[i] + " ");
System.out.println();
//b) every element at an even index (on a single line)
for(int i = 0; i < 10; i+=2)
System.out.print(randInt[i] + " ");
System.out.println();
//c) every even element (on a single line)
for(int i = 0; i < 10; i++){
if (randInt[i] % 2 == 0)
System.out.print(randInt[i] + " ");
}
System.out.println();
//d) all elements in reverse order (on a single line)
for(int i = 9; i >= 0; --i)
System.out.print(randInt[i] + " ");
System.out.println();
//e) only the first and last elements (on a single line)
System.out.print(randInt[0] + " "+ randInt[9]);
System.out.println();
}
}