SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:14 | ISBN:9781118771334 | Edition: 6

Question

Write a pseudocode description of a method that reverses an array of n integers, so that the numbers are listed in the opposite order than they were before, and compare this method to an equivalent Java method for doing the same thing.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Pseudocode:

 

step 1: initilize array using new int[] { }
step 2:    use for loop to print orginal array
     for int i = 0; i < arraylength; i increment
step 3:     print the array using print command

   print array in reverse order
    
step 4:    run the array in loop
step 5:    inilizie i to point last element in the array
    for int i = arraylength-1; i >= 0 ; i decrement
step 6:    print the array

 

//java code to write array in reverse

package java_problems_datastructures;

public class ReverseAnArray {
	// initialize array
	static int[] arrayOfIntegers = {2,5,8,56,23,9,11};
	   
	   // Driver method
	   public static void main(String args[]) {
	         
		     // call the method
	         reverseArray(arrayOfIntegers);

	   }

	   public static void reverseArray(int[] arr) {
		   
		   	   // Print the array as it is 
	           System.out.println("Array before reverse operation : ");
	           for(int i = 0 ; i < arrayOfIntegers.length; i++) {
	           System.out.print(arrayOfIntegers[i] + " ");
	          
	           }
               // Print the array reading from last index first
	           System.out.println(" \nArray after reverse operation : ");
	           for(int i = arrayOfIntegers.length-1 ; i>= 0 ; i--) {
	           System.out.print(arrayOfIntegers[i]+ " ");
	           }

	   }


	}

Output:

Array before reverse operation : 
2 5 8 56 23 9 11  
Array after reverse operation : 
11 9 23 56 8 5 2 

 

0 0

Discussions

Post the discussion to improve the above solution.