7.4k views
5 votes
Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. SPECIFICATIONS: File name: ArrayBackwards.java Your program must make use of at least one method other than main()to receive full credit (methods can have a return type of void). Suggestion: create and populate the array in the main() method. Make a method for Step 3 below and send in the array as a parameter. Make another method for Step 4 and send in the array as a parameter.

User Natali
by
3.7k points

1 Answer

1 vote

Answer:

The program is as follows:

import java.util.*;

public class Main{

public static void backward(int [] Rndarray, int lnt){

System.out.print("Reversed: ");

for(int itm = lnt-1;itm>=0;itm--){

System.out.print(Rndarray[itm]+" "); } }

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int lnt = input.nextInt();

Random rd = new Random();

int [] Rndarray = new int[lnt];

for (int itm = 0; itm < lnt; itm++) {

Rndarray[itm] = rd.nextInt();

System.out.print(Rndarray[itm]+" ");

}

System.out.println();

backward(Rndarray,lnt); }}

Step-by-step explanation:

This defines the backward() method

public static void backward(int [] Rndarray, int lnt){

This prints string "Reversed"

System.out.print("Reversed: ");

This iterates through the array

for(int itm = lnt-1;itm>=0;itm--){

Each element is then printed, backwards

System.out.print(Rndarray[itm]+" "); } }

The main begins here

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

This gets the array length

int n = input.nextInt();

This creates a Random object

Random rd = new Random();

This declares the array

int [] Rndarray = new int[lnt];

This iterates through the array for input

for (int itm = 0; itm < lnt; itm++) {

This generates a random number for each array element

Rndarray[itm] = rd.nextInt();

This prints the generates number

System.out.print(Rndarray[itm]+" ");

}

This prints a new line

System.out.println();

This passes the array and the length to backward() method

backward(Rndarray,lnt); }}

User Gowerc
by
4.4k points