In: Computer Science
Write a program that initializes an array of 6 random integers and then prints 4 lines of output, containing the following:
1. Only the first and last element
2. Every element at an odd index
3. Every odd element
4. All elements in reverse order
SOURCE CODE
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
Random rd = new Random(); // creating Random object
int[] arr = new int[6];
for (int i = 0; i < arr.length; i++)
{
arr[i] = rd.nextInt(); // storing random integers in an array
//System.out.print(arr[i]+"\t"); //remove // added before this
print statement to see elements in array
}
System.out.print("\n");
System.out.println("Only the first and last element:
"+arr[0]+"\t"+arr[arr.length-1]);
System.out.print("Elements at odd index: ");
for (int i = 1; i < arr.length; i=i+2) //printing elements at
odd index
{
System.out.print(arr[i]+"\t");
}
System.out.print("\n");
System.out.print("Every odd element: ");
for (int i = 0; i < arr.length; i++)
{
if(arr[i]%2!=0) //checking whether the array element is odd
{
System.out.print(arr[i]+"\t");
}
}
System.out.print("\n");
System.out.print("All elements in reverse order: ");
for (int i = arr.length-1; i>=0; i--) //printing array elements
in reverse order
{
System.out.print(arr[i]+"\t");
}
}
}
Screenshot of code and output
Explanation
Program starts with initialization of an array with 6 random integers. To get random numbers, makes use of random class and declaring it's object. Using the object initializing array with random numbers.
After that displaying the first and last element of the array using index. Index of the first element is 0 and index of the last element is length of the array-1.
Next displaying elements at odd index in the array. We already know that array index is ranging from 0 to arraylength-1. A loop ranges from 1 to end of the array is used here because odd index starts from 1. since odd index is alternate, we incrementing the loop counter by 2. Hence we gets the array elements at the odd index.
Then next we want to display the odd elements in the array. For that a loop ranges from starting to end of the array and inside loop checking whether the array element is odd. If it is odd then display that array element.
Finally printing the array elements in the reverse order. For that a loop ranges from the end of the array to starting of the array and inside loop printing each element of the array.