Download presentation
Presentation is loading. Please wait.
Published byMervin Horton Modified over 6 years ago
1
Arrays 1. One dimensional arrays - Review 2. Using arrays
3. Two dimensional arrays
2
One Dimensional Arrays - Review
Declaring (3 different ways): Array of Friends 1 2 3 4 Friends John Jane Sally Peter Julie <type> [ ] <name>; // declare array <name> = new <type> [<num>]; // allocate space
3
One Dimensional Arrays - Review
Method 1: String [ ] Friends; // declare array ... … Friends = new String [5]; // allocation of space
4
One Dimensional Arrays - Review
Method 2: String [ ] Friends = new String [5]; // declaration & // allocation of space
5
One Dimensional Arrays - Review
Method 3: String [ ] Friends = {“John”,“Jane”, //declaration & “Sally”, “Peter”, “Julie”}; // initialization
6
One Dimensional Arrays - Review
Using Arrays: System.out.println(Friends[2]); // displays Sally Friends [2] = “Myah”; // stores Myah Friends [5] = “Thomas”; ** Out of Bounds Error !!! ** nFriends = Friends.length; // 5
7
One Dimensional Arrays - Review
Traversing Arrays: for ( int i=0; i<Friends.length; i++) { System.out.println(Friends[i]); } Output to Screen: John Jane Myah Peter Julie
8
Two Dimensional Arrays
1 2 X O A two-dimensional array with three rows (0,1, and 2) and three columns (0,1, and 2) that represents a tic-tac-toe board. 1 2 Declaration: <type> [ ][ ] <name>; <name> = new <type> [<num>] [<num>];
9
Two Dimensional Arrays
X O 1 2 A two-dimensional array with three rows (0,1, and 2) and three columns (0,1, and 2) that represents a tic-tac-toe board. Declaration (3 different ways): i) String [ ][ ] tttBoard; tttBoard = new String [3] [3]; ii) String [ ] [ ] tttBoard = new String [3] [3]; String [ ] [ ] tttBoard = {{“X”, “O”, “”}, {“”, “O”, “X”}, {“”, “” , “” } };
10
Two Dimensional Arrays
Length Function (2-D Arrays): rows = tttBoard.length; // 3 cols = tttBoard[0].length; // 3 Accessing Function (2-D Arrays): tttBoard [1] [2] = “X”; Value Stored Row 2 Column 3
11
Two Dimensional Arrays
Traversing (2-D Arrays): for ( int row = 0; row < tttBoard.length; row++) { for ( int col = 0; col < tttBoard[0].length; col++) { System.out.println(tttBoard[row][col]); } System.out.println(); Output: X O O X X
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.