Saturday, 20 August 2016

Chapter 7 Exercise 12, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.


*7.12 (Reverse an array) The reverse method in Section 7.7 reverses an array by copying it to a new array. Rewrite the method that reverses the array passed in the argument and returns this array. Write a test program that prompts the user to enter ten numbers, invokes the method to reverse the numbers, and displays the numbers.



import java.util.Scanner;
 
 
public class ProgrammingEx7_12 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  int[] numbers = new int[10];
 
  System.out.print("Enter 10 integers:");
 
  for (int i = 0; i < numbers.length; i++) {
   numbers[i] = input.nextInt();
  }
          int[] reverseNumbers = reverse(numbers);
           
        //Printing both the original array and returned array.
        //This is a good demonstration of what happen when arrays are passed to function.
        //They are both pointing to the same array after the function call.
    
        System.out.println("Pringting the original array:");
  for (int i = 0; i < numbers.length; i++) {
   System.out.print(numbers[i] + " "); 
  }
   
  System.out.println();
        System.out.println("Pringting the returned array:");
  for (int i = 0; i < reverseNumbers.length; i++) {
   System.out.print(reverseNumbers[i] + " "); 
  }
 }
 
 public static int[] reverse(int[] list) {
   
  int temp;
 
  for (int i = 0, j = list.length -1; i < list.length/2; i++, j--) {
   temp = list[j];
   list[j] = list[i];
   list[i] = temp;
  }
 
  return list;
 }
 
}

No comments :

Post a Comment