logotransparent.png

Legion of Learners

www.lol-101.com

  • Home

  • Classrooms

  • Courses

  • About Us

    • Executive Team
    • Board Members
  • Resources

  • More

    Use tab to navigate through the menu items.
    To see this working, head to your live site.
    • Categories
    • All Posts
    • My Posts
    sfolax6776
    Feb 20, 2020
      ·  Edited: Nov 09, 2020

    7.9 Can a function return an array?

    in Introduction to Java

    A. Introduction

    A function can take a 1-D or 2-D array as input and manipulate the data elements. Once the function finishes processing, how to return the new array back to the caller?


    B. How to reflect a 2-D array vertically as shown below? i.e. turn A into B by moving the top row to the bottom, 2nd row to the 2nd but last... etc?


    class Reflect2DArray {  
        public static int[][] verticalReflect(int[][] arrayX){
                // Swap rows up and down
        int[][] temp = new int[arrayX.length][arrayX[0].length];
    	 for (int row = 0; row < arrayX.length; row++)
    		for (int col = 0; col < arrayX[0].length; col++)
    			temp[arrayX.length - row -1][col] = arrayX[row][col];
        return temp;
      }
      
      public static void print2DArray(int[][] arrayX){
        for(int[] s:arrayX){
          for(int sp: s)
            System.out.print(sp + " ");
        	System.out.println();
        }
      }
      
      public static void main(String[] args) {
        int[][] speed =   {  {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95},{88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99},{50, 65, 92, 87, 94}, {43, 98, 78, 56, 99}  };
        int[][] vReflect = verticalReflect(speed);
        print2DArray(speed);
        print2DArray(vReflect);
      }
    }

    C. Try:

    Create a function that rotates the elements of a 1-D array by one position, moving the initial element to the end of the array, as shown at right.



    0 comments
    0
    0 comments

    Questions? Email us at legionoflearners@gmail.com or join our WeChat group!

    • lol-101dotcom

    ©2020 Legion of Learners