Write a recursive method in java to reverse the values stored in an integer arra
ID: 645989 • Letter: W
Question
Write a recursive method in java to reverse the values stored in an integer array. Place the method where indicated in the following program. Run the program and paste a screenshot of the output.
// Import classes
import java.util.Random;
//==============================================================
// class Example
//==============================================================
public class Example
{
//--------------------------------------------------------------------
// randomizeArray
//--------------------------------------------------------------------
private static void randomizeArray (int[] arr, int upperLimit)
{
// Loop to generate and store in array random numbers from 1 to upperLimit
Random rand = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = rand.nextInt(upperLimit) + 1;
}
//--------------------------------------------------------------------
// printArray
//--------------------------------------------------------------------
private static void printArray (String heading, int[] arr)
{
// Loop to print array numbers
System.out.print(heading + ": [");
for (int i = 0; i < arr.length; i++)
System.out.printf("%3d", arr[i]);
System.out.println("]");
}
//----------------------------------------------------------------
// reverseArray
//----------------------------------------------------------------
private static int[] reverseArray (int[] arr)
{
WRITE THE CODE HERE
}
//----------------------------------------------------------------
// main
//----------------------------------------------------------------
public static void main (String[] args)
{
// Declare constants
final int ARRAY_SIZE = 8;
// Declare variables
int[] arr = new int[ARRAY_SIZE];
// Show application header
System.out.println("Welcome to Array Reverser");
System.out.println("--------------------------");
// Place random numbers in and print array
randomizeArray(arr, 99);
printArray (" Original array", arr);
// Reverse and print array
arr = reverseArray(arr);
printArray ("Reversed array", arr);
// Show application close
System.out.println(" End of Array Reverser");
}
}
Explanation / Answer
Write a program to reverse an array
Iterative way:
1) Initialize start and end indexes.
start = 0, end = n-1
2) In a loop, swap arr[start] with arr[end] and change start and end as follows.
start = start +1; end = end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.