第 1 页,共 13 页

�AP Java 2D Arrays

Warm up Kahoot: 8775687

Essential Questions

  • How do you create and use a 2D array?

Learning Target

Be able to use a 2D array in solving a challenge.

第 2 页,共 13 页

Outline

  • Review Kahoot
  • AP Practice questions for 2D arrays

第 3 页,共 13 页

What is the value of sum are the code is executed?

第 4 页,共 13 页

第 5 页,共 13 页

第 6 页,共 13 页

第 7 页,共 13 页

第 8 页,共 13 页

第 9 页,共 13 页

2-D Arrays: Dimensions

  • In Java, a 2-D array is a 1-D array of 1-D arrays, its rows. Each row is stored in a separate block of consecutive memory locations.
  • If m is a 2-D array, then m[k] is a 1-D array, the k-th row.
  • m.length is the number of rows.
  • m[k].length is the length of the k-th row.

12-9

第 10 页,共 13 页

More Two D

  • Internally, Java stores 2 dimensional arrays as an array of arrays:
  • int [][] nums = new int[5][4];
  • The above is really equivalent to a 3-step process:
  • // create the single reference nums (yellow square)
  • int [][] nums;
  • // create the array of references (blue squares)
  • nums = new int[5][];
  • // this create the second level of arrays (red squares)
    • for (int i=0; i < 5 ; i++)
      • nums[i] = new int[4]; // create arrays of integers

第 11 页,共 13 页

Tic-Tac-Toe

  • Write a program that will model playing Tic-Tac-Toe using a 2D array to store the x’s, blanks, and O’s.
    • The program needs to let each user have a turn
    • The user can determine if the game is over
  • Push: Computer vs. user
  • Push: Using logic so the computer will never lose.

12-11

Add 1 Push to the assignment

第 12 页,共 13 页

Magic Square

  • A magic square[1] is a n by n square grid (where n is the number of cells on each side) filled with distinct positive integers in the range {1,2,...,n2} such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal

12-12

第 13 页,共 13 页

Magic Square Program

  • Level 1: Write a program that will take as input the values for each cell of a 3x3 potential magic square and determine if the square is magic.
  • Level 2: Write a program to generate 3x3 magic squares. Using an algorithm rather than just hard coding a found solution.
  • Level 3: Modify this to handle n x n magic squares where n is an odd number. (See Google Doc describing an algorithm on the class website.)

12-13

Add 1 Push to the assignment