Presentation is loading. Please wait.

Presentation is loading. Please wait.

Two Dimensional Array Mr. Jacobs.

Similar presentations


Presentation on theme: "Two Dimensional Array Mr. Jacobs."— Presentation transcript:

1 Two Dimensional Array Mr. Jacobs

2 Two Dimensional Array An array can be two dimensional, which is sometimes referred to as a table. A two dimensional array consists of both rows and columns of elements. For example this is a 3 row by 4 column array. To reserve storage for this array, both the number of rows and number of columns must be included in the array’s declaration.

3 Declaring Two Dimensional Arrays
Array Declaration statements use the following format : variableType arrayName[# of Rows][# of Cols.; Example) int numbers[10][3]; // A 10 row by 3 column table double ages[2][20]; // A 2 row by 20 column table string names[10][10]; // A 10 row by 10 column table

4 Modifying Elements Elements in an array can be modified by stating the name of the array and the index of the element which you would like to modify just like a normal array. You have to have both the row and the column index. Example: int arry[4][5]; arry[0][3] = 27; // The element at row index 0 and column index 3 now has a value of 27

5 Accessing Elements Elements in an array can be accessed and printed by referring to the name of the array and the specific element of which you would like to access Example) int arry[5][2]; // Declare integer array of size 5x2 arry[0][2] = 23; cout << arry[0][2] << endl; // Prints: 23

6 Printing A Table In order to print a table, or all of the two dimensional array, you will need to use a nested for loop. Example: for(int r=0;r<3;r++){ for(int c=0;c<5;c++){ cout<<setw(4)<<nums[r][c]; } cout<<endl;

7 Print Out

8 String Arrays Two Dimensional Arrays can be made of strings as well as integers and doubles Example) string locations[1][4]; locations[1][3] = “Bahamas”;

9 Array Initialization When declaring an array, we can also initialize all of the elements to a starting value Example) int nums[3][5]={2,5,9,4,6, ,35,65,98,12, 26,44,66,77,99 };

10 Array Initialization What does the code below print out? int nums[3][5]={2,5,9,4,6, 22,35,65,98,12, 26,44,66,77,99 }; cout << num[1][4] << endl;

11 Array Initialization What does the code below print out? int nums[3][5]={2,5,9,4,6, 22,35,65,98,12, 26,44,66,77,99 }; cout << num[1][4] << endl; Prints out 12


Download ppt "Two Dimensional Array Mr. Jacobs."

Similar presentations


Ads by Google