180 likes | 296 Views
Two-Dimensional Arrays Lesson xx. Objective. We will cover the following topics that deal with two-dimensional array: Declaration Subscripts Initialization Operations Application in a program. Two Dimensional Array Declaration. int m [3] [4];. col 1. col 2. col 3. col 0.
E N D
Objective • We will cover the following topics that deal with two-dimensional array: • Declaration • Subscripts • Initialization • Operations • Application in a program
Two Dimensional Array Declaration int m [3] [4]; col 1 col 2 col 3 col 0 row 0 row 1 row 2
More Examples of 2-D Arrays float taxTable [10] [15]; double d [50][50]; char nameList [100] [20]; int t [5] [6];
Subscripts int m [3] [4]; col 1 col 2 col 3 col 0 row 0 m [1] [3] row 1 row 2 m [2] [1]
Initialization with { } int m[2][3] = {{3, 6, 7}, {4, 7, 5}}; 4 3 6 7 5 7
Initializing Partial Rows int m[2][3] = {{3, 6 }, {4} }; 4 3 0 3 6 6 0 0 4 0 0 0 int m[2][3] = { 3, 6 , 4 };
Two-Dimensional Array Operations int m[4][5] = {0}; int x = 0; int a = 1; m[2][3] = 17; m[3][3] = a + m[2][3]; if (m[1][2] >= x) cin >> m[1][3]; cout << m[1][0] << endl;
Two-Dimensional Array Operations int m[4][5] = {0}; int x = 0; int a = 1; m[2][3] = 17; m[3][3] = a + m[2][3]; if (m[1][2] >= x) cin >> m[1][3]; cout << m[1][0] << endl;
Program Description Write a program for a shipping company that: 1. Reads in an origination and destination zone. 2. Reads in the weight of the package. 3. Looks up the price/lb for shipping the package. 4. Computes the cost for shipping the package.
Table .50 1.00 1.25 2.00 1.00 .50 .82 .44 .82 .50 1.2 5 .89 .50 .69 .47 2.00 1 2 3 4 Zone 1 2 3 4
Program Listing #include <iostream> using std::cin; using std::cout; using std::endl; int main() { double chart[4][4] = {{0.5, 1.0, 1.25, 2.0}, {1.0, 0.5, 0.89, 0.47}, {1.25, 0.82, 0.5, 0.69}, {2.0, 0.44, 0.82, 0.5}}; int o, d; float w; cout << "Enter origination zone, destination zone & weight: "; cin >> o >> d>> w; cout << "The cost for sending your package is " <<( chart[o-1][d-1 ] ) * w << endl; return 0; }
Table int main() { double chart[4][4] = {{0.5, 1.0, 1.25, 2.0}, {1.0, 0.5, 0.89, 0.47}, {1.25, 0.82, 0.5, 0.69}, {2.0, 0.44, 0.82, 0.5}}; 1.25 1.00 2.00 .50 .50 .44 1.00 .82 .89 .50 1.2 5 .82 .69 .47 2.00 .50 chart 0 1 2 3 0 1 2 3
Declaration and Input int o, d; float w; cout << "Enter origination zone, destination zone & weight: "; cin >> o >> d>> w;
Compute Cost cout << "The cost for sending your package is " <<( chart[o-1][d-1 ] ) * w << endl; return 0; }
Summary In this module, we learned the following about two-dimensional arrays: • Declaration • Subscripts • Initialization • Operations • Application in a program