How to write a reversed array with random numbers in array form JAVA

Solution for How to write a reversed array with random numbers in array form JAVA
is Given Below:

  • Write code that creates and populates an array of size 25 with random numbers between 1-50.

  • Display the array contents from the first to last element.

  • Display the array from the last to the first element.

I am learning how to program from a book. There is only one example of reversing, but it is not an array. I am able to print the first array, but not the second reversed array. It is reversed, but it is not in array form.

import java.util.*;
public class flip
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
        int[] rn = new int[25];
        Random r = new Random();;
        for(int i = 0; i < 25; i++)
        {
            rn[i] = r.nextInt(50) + 1;
        }
        System.out.println(Arrays.toString(rn));
        for(int i = 24; i >= 0; i--)
        {
            System.out.println(rn[i]);
        }
    }
}

Just replace System.out.println(rn[i]); with System.out.print(rn[i] + " "); to print all values of rn in one line.

If you want the output to be just like the array you can try this:

public static void main(String[] args)
{
    int[] rn = new int[25];
    Random r = new Random();;
    for(int i = 0; i < 25; i++)
    {
        rn[i] = r.nextInt(50) + 1;
    }
    System.out.println(Arrays.toString(rn));
    System.out.print("[");
    for(int i = 24; i >= 0; i--)
    {
        System.out.print(rn[i]);
        if(i > 0) {
            System.out.print(", ");
        }
    }
    System.out.println("]");
}

Output of main() method call is:

[36, 48, 29, 4, 43, 23, 36, 40, 21, 12, 29, 12, 24, 36, 37, 16, 43, 5, 4, 30, 47, 28, 14, 19, 44]
[44, 19, 14, 28, 47, 30, 4, 5, 43, 16, 37, 36, 24, 12, 29, 12, 21, 40, 36, 23, 43, 4, 29, 48, 36]

Update:

You can also reverse rn array and print it after that:

public static void main(String[] args)
{
    int[] rn = new int[25];
    Random r = new Random();;
    for(int i = 0; i < 25; i++)
    {
        rn[i] = r.nextInt(50) + 1;
    }
    System.out.println(Arrays.toString(rn));


    for(int i = 0; i < rn.length / 2; i++)
    {
        int temp = rn[i];
        rn[i] = rn[rn.length - i - 1];
        rn[rn.length - i - 1] = temp;
    }
    System.out.println(Arrays.toString(rn));
}

Output of main() method call is:

[23, 40, 47, 7, 39, 14, 6, 7, 42, 23, 47, 45, 30, 20, 27, 15, 2, 6, 34, 5, 29, 22, 40, 22, 10]
[10, 22, 40, 22, 29, 5, 34, 6, 2, 15, 27, 20, 30, 45, 47, 23, 42, 7, 6, 14, 39, 7, 47, 40, 23]